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

Time:07-07

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 onm ouseOver={handleMouseOver} onm ouseOut={handleMouseOut} key={item.id}>
                        {isHovering ? 
                            <Card.Body>
                                <p>{item.item_description}</p>
                            </Card.Body>
                        :
                            <Card.Body>
                            </Card.Body>
                        }
                        <Card.Footer>

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

CodePudding user response:

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 onm ouseOver={handleMouseOver} onm ouseOut={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>
  );
}

CodePudding user response:

Your "isHovering" state should also be an array, where you store the hover state for every card. Then on hover set "isHovering" to true only for the right card.

  • Related