Home > Mobile >  React / How can I do so onMouseEnter doesn't update all the elements?
React / How can I do so onMouseEnter doesn't update all the elements?

Time:09-04

Hello

I have used a map function to create a list of elements.

When there is a mouseEnter in one of these elements, it should change the visibility of the sibling element (div classname="prompt")

The problem is : this changes the visibility for all of them.

Even if I add an index to the (div classname="prompt") it doesn't work.

Here are the key code involved :

const [showElement, setShowElement] = useState(false);


return (

    
{images.map((index, i) => {
   return (
   <div className="itemVert" >
      <div className="item" key={i}
       onm ouseEnter={() => setShowElement(true)} onm ouseLeave={() => setShowElement(false)}>
            <img src={`./images/${myjson.images[index].name}`} alt="" />          
       </div>

    <div className="prompt"
       style={{ visibility: showElement ? 'visible' : 'hidden' }}
       >{myjson.images[index].prompt}
    </div>   
  </div> 
 })

CodePudding user response:

To show the prompt element for each item, I suggest you should have a state to store the current hover index rather than a boolean, something like this:

const [showIndex, setShowIndex] = useState(null);

...

onMouseEnter={() => setShowIndex(i)}
onMouseLeave={() => setShowIndex(null)}

...

style={{ visibility: showIndex === i ? 'visible' : 'hidden' }}

this will help distinguish which element is being hovered.

I've made a working example here: https://stackblitz.com/edit/react-nasf1b?file=src/App.js

  • Related