Home > Blockchain >  React: Card component share same state
React: Card component share same state

Time:02-14

Created RenderCard component which creates multiple cards for given data.

enter image description here

I am creating bulk selection of card means selecting multiple cards. So when user click on circle present at the top left then that circle become check circle

enter image description here

So here the issue is that all card gets selected when user click on any card. So I want only that card select which users click

const Card = () => {
  const [cardSelect, setCardSelect] = useState(false)
  const onm ouseEnter =  () => {
    console.log("onMouseEnter1")
  }

  const onm ouseLeave =  () => {
    console.log("onMouseLeave1")
  }

  const logMessage =  () => {
    setCardSelect(prevCheck => !prevCheck);
  }
  const RenderCard = () => {
    return album.map(item => {
      return (
        <Col className='container' onm ouseEnter={onMouseEnter} onm ouseLeave={onMouseLeave} key={item.title} md='2'>
          <Card>
            <div>
              <Link to={`/pages/blog/detail/${item.id}`}>
                <CardImg className='img-fluid image' src={item.img} alt={item.title} top />
              </Link>
            </div>
              <div className='select-card'>
              {cardSelect ? <CheckCircle onClick={logMessage} /> : <Circle onClick={logMessage}  />}
            </div>
            <CardBody>
              <CardTitle className="image2 te" >
                  <b>{item.title}</b>
              </CardTitle>
              <CardText>{item.comment} Comments</CardText>
            </CardBody>
          </Card>
        </Col>
      )
    })
  }
  return (
    <>
      <Row>
        <RenderCard />
      </Row>
    </>
  )
}

Anyone can point me in the right direction where I am doing mistakes.

Thanks

CodePudding user response:

If i understand you correctly i would suggest that you should wrap anything that is inside the return statement and refactor it to its own component, and then pass item as prop in that component and make the clickhandler inside that component. like this:

const RenderCard = () => {
    return album.map(item => {
      return ( <Component item={item} />)
  }

Now the component have its own state that shows either its clicked or not clicked

CodePudding user response:

With this line of code : cardSelect ? <CheckCircle onClick={logMessage} /> : <Circle onClick={logMessage} />

You are saying : "If cardSelect is true, then render CheckCircle component, otherwise, render Circle component and do that for all items in album list". So when the state changes, it will render only one type of object CheckCircles, or Circles as many times as there are elements in the album list for which you are calling the map method.

That is why you are seeing all checked circles when you set your variable cardSelect to true.

  • Related