I have multiple images and onClick that will be display in another div this is working fine in React but now I want to display first image by default in another div, how can I do that?
My code:
render() { const imageClick = (selectedImg) => { this.setState({ selectedImg }) } return ( <div> <img src="images/1.png" onClick={() => imageClick(1)} /> <img src="images/2.png" onClick={() => imageClick(2)} /> <img src="images/1.png" onClick={() => imageClick(1)} /> <img src="images/2.png" onClick={() => imageClick(2)} /> <div className="newDiv"> <img src={`images/${this.state.selectedImg}.png`} /> // Get the selected image from this.state </div> </div> ) }
You need to set the initial state of image to 1
. For default the will load the first image to div
state = {
selectedImg:1
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.