Basit
Basit

Reputation: 367

changing image source by dealing with state in Reactjs

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;

Upvotes: 0

Views: 5093

Answers (1)

Ravi Roshan
Ravi Roshan

Reputation: 1207

You can take another/better approach of doing this.

Keep 2 variables in your state i.e. image array [don't mutate it] and selectedImageIndex to keep track of currently selected/clicked thubnail.

Whenever you click on any thumbnail image, just change the selectedImageIndex and the target image src can point to <img src={this.state.images[this.state.selectedImageIndex]["img"]} alt="" />

Here is the working example: https://codepen.io/raviroshan/pen/QVraKo

Upvotes: 1

Related Questions