Reputation: 53
lets say that i have a function that returns:
return (
<div>
<ul>
<div><img className='privewimg' src={user.img1}/></div>
<div><img className='privewimg' src={user.img2}/></div>
<div><img className='privewimg' src={user.img3}/></div>
</ul>
</div>
);
now, i want to add the functions onMouseEnter and onMouseLeave
so every time that the mouse enter to some div, the image of the spesific div will change to some other picture (for example "xxx.png")
can anyone help me with this?
thanks,
Upvotes: 1
Views: 3475
Reputation: 289
Use Component state to update image url.
changeImage = (img) => {
this.setState({
user: {
[img]: newImageUrl
}
});
}
resetImage = (img) => {
this.setState({
// set the old image
});
}
render() {
const { user } = this.state;
return (
<div>
<ul>
<li onMouseEnter={() => this.changeImage('img1')} onMouseLeave={() => this.resetImage('img1')}>
<img className='privewimg' src={user.img1}/>
</li>
</ul>
</div>
);
}
Upvotes: 0
Reputation: 1125
You can use the state for the image source. And whenever the mouse hovers over the div, change the image source. Something like this:
handleMouseOver() {
this.setState({imageSrc: 'dummySrc1'});
}
handleMouseLeave() {
this.setState({imageSrc: 'dummySrc2'});
}
render() {
return(
<div onMouseEnter={this.handleMouseEnter} onMouseLeave={this.handleMouseLeave}>
<img src={this.state.imageSrc}/>
</div>
);
}
You can also use the redux store for the image path.
Upvotes: 3