Reputation: 25
I'm displaying my data using the map function, and I want to add CSS style to for specific index when the mouse enters in the div, but when I tried to hover the div, all data list showing the same style at the same time. Can someone help me with this concern?
Here is the code
const [view, setView] = useState(false);
const Show = (index) => {
setView(true);
alert(index);
};
const Hide = (index) => {
setView(false);
};
{data.map((res, index) => (
<div key={index}>
<div
className={classes.blogCard}
onMouseEnter={() => Show(index)}
onMouseLeave={() => Hide(index)}
>
<h1>{res.title}</h1>
<div
className={
view
? classes.blogLink + " " + classes.hoverLink
: classes.blogLink
}
>
<h5 className={classes.blogListTitlle}>{res.title}</h5>
{view ? <p className={classes.text}>{res.desciption}</p> :false }
</div>
</div>
))}
Upvotes: 1
Views: 431
Reputation: 442
See the solution below. It's best if you split this into 2 components: one is the articles container and the article component itself. Control the addition of extra CSS styles by adding or removing the view
class. In your CSS code add all the extra styles in this class.
const data = [{ title: 'Article 1' }, { title: 'Article 2' }, { title: 'Article 3' }];
const App = () => {
return (
<div>
{data.map((res, index) => (
<Article key={index} title={res.title} />
))}
</div>
)
}
const Article = ({ title }) => {
const [view, setView] = React.useState('');
const handleMouseEnter = () => setView('view');
const handleMouseLeave = () => setView('');
return (
<div className={`some-class-name ${view}`}
onMouseEnter={handleMouseEnter}
onMouseLeave={handleMouseLeave}>
<h1>{title}</h1>
</div>
)
}
Upvotes: 1