I am trying to make an Image slider like e-commerce product in Reactjs.
In javascript it's pretty simple, we only need to change the image source, but how to do it in React? because in React we have to deal with state.
First I mapped out all four images(state) as side images(className ='sideImages') then hardcoded the first image of state as display image. Now I want when I click any of the side images it becomes display image (className='display') I hope I am clear.
Here is my component
import React, { Component } from 'react';
class App extends Component {
state = {
images: [
{
id: 1,
img: "https://images.pexels.com/photos/1"
},
{
id: 2,
img: "https://images.pexels.com/photos/2"
},
{
id: 3,
img: "https://images.pexels.com/photos/3"
},
{
id: 4,
img: "https://images.pexels.com/photos/4"
}
]
};
onClickHandler = () => {
this.setState({
// this.state.images[0]['img']: 'this.src'
})
}
render() {
const sideImages = this.state.images.map(image => (
<img key={image.id} src={image.img} alt="" />
));
return (
<div className="imageSlider">
<div onClick={this.onClickHandler} className="sideImages">
{sideImages}</div>
<div className='display'>
<img src={this.state.images[0]['img']} alt="" />
</div>
</div>
)
}
}
export default App;
setStateis replacing an object, which contains an array of objects with a string "this.src". You have to replace it with the same thing. YoursetStateshould keep the same data structure, just replace it with a new object of the same data structure but different values.