Currently, I am delving into the world of React and have come across a piece of code that successfully applies an opaque white overlay over an image when hovering over a button. This functionality is working as expected:
class Product extends Component {
constructor(props) {
super(props);
// 1. bind your functions in the constructor.
this.mouseOver = this.mouseOver.bind(this);
this.mouseOut = this.mouseOut.bind(this);
this.state = {
hover: false
};
}
// 2. bind it with fat arrows.
mouseOver = () => {
this.setState({hover: true});
}
mouseOut() {
this.setState({hover: false});
}
render() {
return (
<Link to={"/products/"+this.props.value.uid}>
<button className="Product" onMouseEnter={this.mouseOver.bind(this)} onMouseLeave={this.mouseOut.bind(this)}>
<img className="ImageGrid" src={this.props.value.media}/>
{this.state.hover ? (
<div className="ImageOverlay">
<div className="TextOverlay">
<p><b>{this.props.value.name}</b></p>
<p>${this.props.value.price}</p>
</div>
</div>) : null}
</button>
</Link>
);
}
}
I find myself contemplating the scenario where I want to alter an image rendered by a different component. Instead of employing an overlay div, I aim to modify said image's appearance through a CSS setting like applying the filter: grayscale(100%). The specific image I wish to target within another component is:
<img className="PicBox" src={this.state.img[sid-1]} />
This image is generated by a separate component.
In order to execute my proposed plan, I believe the following strategy may be beneficial:
The original component (where the hover effect occurs) should possess a prop named "state" which indicates whether the hover action is taking place or not.
Within the second component responsible for rendering ImageX, access to the Hover component's prop is necessary to check its state and determine how to display the image (grayscale or colored).
How can I retrieve the state of the hover component from within another component?
(Alternatively, any guidance regarding the correctness of my approach would be greatly appreciated)