Home > Enterprise >  Change class or style of specific element using events React
Change class or style of specific element using events React

Time:06-01

I am having difficulties with React, I created a few hidden overlay divs within their own respective Card parent using map. I want the overlay div to be visible, but only for the Card that my mouse is hovering over. I'm using bootstrap-react.

  const [showResults, setShowResults] = React.useState(false);
  const onEnter = () => setShowResults(true);
  const onExit = () => setShowResults(false);

{filterDataState &&
            filterDataState.map((type: any) => (
              <Col className='p-0 mClass' onm ouseEnter={onEnter} onm ouseLeave={onExit}>
                      <div className={ showResults ?  undefined :'d-none' } > overlay placeholder</div>
                <Card className='m-auto' bg='dark' text='white' key={type.id} style={{}}>
                  <Card.Img src={type.img} />
                  <Card.Header className='text-center'><h6>{type.nome}</h6></Card.Header>
                  <Card.Body className='text-center'>{type.content}</Card.Body>
                </Card>
              </Col>
            ))}

The main problem is that every time I hover over the Card, the overlay div is displayed on all Cards, as opposed to just the one I hovered on.

CodePudding user response:

You can use the key or an ID to be sure witch is the card that is mouse enter:

const [showResults, setShowResults] = React.useState(false);
  const onEnter = (id) => setShowResults(id);
  const onExit = () => setShowResults(false);

{filterDataState &&
            filterDataState.map((type: any) => (
              <Col className='p-0 mClass' onm ouseEnter={onEnter(type.id)} onm ouseLeave={onExit}>
                      <div className={ showResults === type.id ?  undefined :'d-none' } > overlay placeholder</div>
                <Card className='m-auto' bg='dark' text='white' key={type.id} style={{}}>
                  <Card.Img src={type.img} />
                  <Card.Header className='text-center'><h6>{type.nome}</h6></Card.Header>
                  <Card.Body className='text-center'>{type.content}</Card.Body>
                </Card>
              </Col>
            ))}

add to the onEnter function the id param and check it with showResults === type.id

  • Related