Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How can i target a specific item of list on hover in React?

I’m new in React. I want to show a div element when I hover one list item. But now the change is happening on all of them. I want the div to appear only on the hovered list item.

This is the LabelList components which is the parent component of one list item.

const LabelList = ({labelIcon, createFolderIcon}) => {


  const [isHover, setIsHover] = useState(false);

  const handleMouseEnter = (e) => {
    console.log(e.target)
    setIsHover(true);
    
  }

  const handleMouseOut = () => {
    setIsHover(false);
  };

  return (
    <ul className=' pl-3 pb-3 label-list'>
        <ListItem className='active ' icon={labelIcon} handleMouseOut={handleMouseOut} handleMouseEnter={handleMouseEnter} isHover={isHover}>
          <p>February</p>
          <div className="flex ml-auto mr-3"> 
            {isHover && (
              <EditDelete />
            )}</div>
        </ListItem>
        
        <ListItem icon={labelIcon} handleMouseOut={handleMouseOut} handleMouseEnter={handleMouseEnter} isHover={isHover}>
          <p>June</p>
        </ListItem>
        <ListItem icon={createFolderIcon}>
          <p style={{color:"#6F76A7;"}}>Create new label</p>
        </ListItem>
    </ul>
  )
}

This is the component for the single list item.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel


  return (
    
    <li className={`list-item flex align-middle items-center mb-1 ${className}`} onMouseEnter={handleMouseEnter} onMouseOut={handleMouseOut}>
      
      <ListItemIcon icon={icon}/>
        {children}
    </li>
  )
}  ```

>Solution :

The problem is that you are using the same and only state ‘isHover’ for all the list items.

This way, if you hover on one list item, isHover will be set to true, and all the other list items will start behaving as if you hovered on them too.

What you should do is put the const[isHover, setIsHover] = useState(false) inside the ListItem component so that each list item can check for their own hover state.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading