Reputation: 600
I am working on a reacts app and the requirement is to change the image when that row is hovered.
The codesand of the code is attached.
It works fine but the problem is whenever any row is hovered, getData() method fires each time.
How can I stop it fire each time the row is hovered?
https://codesandbox.io/s/react-hooks-usestate-nkymg
Thanks
Upvotes: 1
Views: 165
Reputation: 1211
You can do this by keeping index of hovered row:
class MyTable extends Component {
img1 = "https://img.icons8.com/material/4ac144/256/camera.png";
img2 = "https://img.icons8.com/material/4ac144/256/user-male.png";
constructor(props) {
super(props);
this.state = {
list: ["Pete", "Peter", "John", "Micheal", "Moss", "Abi"],
hoverIndex: -1
};
}
// Call get data everywhere you want fetch data or do some operatiosn on it
getData = () => {
console.log("getData called!");
this.setState({
...this.state,
list:
this.state.list.length > 3
? this.state.list.slice(0, 3)
: this.state.list.slice(3, 5)
});
};
handleHover = index => {
this.setState({ ...this.state, hoverIndex: index });
};
handleOut = () => {
this.setState({ ...this.state, hoverIndex: -1 });
};
render() {
return (
<div>
{this.state.list.map((name, index) => (
<div
key={name}
onMouseOver={() => this.handleHover(index)}
onMouseOut={this.handleOut}
style={{ display: "flex", justifyContent: "space-around" }}
>
<div> {name} </div>
<div>
<img
src={this.state.hoverIndex === index ? this.img2 : this.img1}
height="30px"
width="30px"
alt=""
/>
</div>
</div>
))}
</div>
);
}
}
And here is my link to the working version demo.
Upvotes: 1