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.
return (
<li className={`list-item flex align-middle items-center mb-1 ${className}`} onm ouseEnter={handleMouseEnter} onm ouseOut={handleMouseOut}>
<ListItemIcon icon={icon}/>
{children}
</li>
)
} ```
CodePudding user response:
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.