0

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;
1
  • your setState is replacing an object, which contains an array of objects with a string "this.src". You have to replace it with the same thing. Your setState should keep the same data structure, just replace it with a new object of the same data structure but different values. Commented Sep 12, 2018 at 17:17

1 Answer 1

1

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.