How do I show data on one card when hovering and not on all?

Okay there is definitely a quick solution for this I just can’t figure out.

Just a description of what I am trying to do:

Whenever I hover over a certain card, I would like to see the description of that item and only that item. But instead what’s obviously happening, as you can see from my code, is every single cards description is showing.

I rewrote a simpler version of the code by taking out any unnecessary pieces. Everything is imported correctly, styling and classNames were removed as well.

export function Items() {
    const [items, setItems] = useState([])
    const [isHovering, setIsHovering] = useState(false)

    useEffect(() => {
        setItems(Data)
    }, [])
    
    function handleMouseOver() {
        setIsHovering(true)
    }
    function handleMouseOut() {
        setIsHovering(false)
    }

    return(
        <div>
            {items.map(item => {
                return(
                    <Card onMouseOver={handleMouseOver} onMouseOut={handleMouseOut} key={item.id}>
                        {isHovering ? 
                            <Card.Body>
                                <p>{item.item_description}</p>
                            </Card.Body>
                        :
                            <Card.Body>
                            </Card.Body>
                        }
                        <Card.Footer>

                        </Card.Footer>
                    </Card>
                )
            })}
        </div>
    )
}

>Solution :

As far as I can see you don’t need to put this logic into parent component, and also it makes everything more complex, since it’s hard to manage hovering. I would create new chlid component and manage this state out there internally.

export function Item({item}) {
  const [isHovering, setIsHovering] = useState(false);

  useEffect(() => {
    setItems(Data);
  }, []);

  function handleMouseOver() {
    setIsHovering(true);
  }
  function handleMouseOut() {
    setIsHovering(false);
  }

  return (
    <Card onMouseOver={handleMouseOver} onMouseOut={handleMouseOut}>
      {isHovering ? (
        <Card.Body>
          <p>{item.item_description}</p>
        </Card.Body>
      ) : (
        <Card.Body></Card.Body>
      )}
      <Card.Footer></Card.Footer>
    </Card>
  );
}

export function Items() {
  const [items, setItems] = useState([]);

  return (
    <div>
      {items.map(item => (
        <Item key={item.id} item={item} />
      ))}
    </div>
  );
}

Leave a Reply