I
I
ironmansl2019-10-16 15:27:56
React
ironmansl, 2019-10-16 15:27:56

How can I make it so that instead of numbers, the image corresponding to the number is displayed when the buttons are pressed?

At the moment I have two buttons, the prev button decreases the number by 1, and the next button increases it by 1.
I need to do something so that instead of the number to the right of the buttons, or somewhere on the page, the images that I have in the array are displayed :
image banana = number 1
watermelon = number 2
strawberry = number 3
That is, as it should be:
There are buttons on the page and a banana picture on the right, so in state I set the value 1 and number one corresponds to the number 1, when I pressed the next button, a watermelon was displayed (number 2), clicked next again, strawberries were displayed and so on in a circle. If the number is greater than 3, the picture is displayed under the number 1, and if it is less than 1, then under the number 3.
What do I need to add / change in my code to implement this?
PS Maybe it would be better to add images to the state and not to the items variable?
Here is my source code:

const items = [
    { img: "https://pbs.twimg.com/profile_images/3117087049/697e0334a13361c6ab68ce00aefefa4f.jpeg" },
    { img: "http://vkclub.su/_data/gifts/134.jpg" },
    { img: "https://encrypted-tbn0.gstatic.com/images?q=tbn%3AANd9GcTBIqdLHvhxu4LAxudRrH2OoJSctYh9pw3NyziKUwbpp77tsOvu" }
];

class App extends React.Component {
  state = {
    image: 1,
  }

  plus = () => {
    this.setState({
      image: this.state.image + 1,
    });
  }
  
  minus = () => {
      this.setState({
      image: this.state.image - 1,
    });
  }
  
  render() {
    return (
      <div><button onClick={this.minus}>Prev</button>
        <button onClick={this.plus}>Next</button>
        {this.state.image}
      </div>
    );
  }
}

ReactDOM.render(<App />, document.getElementById('root'));

and in the sandbox:
https://jsfiddle.net/51jevc4y/

Answer the question

In order to leave comments, you need to log in

1 answer(s)
0
0xD34F, 2019-10-16
@ironmansl

{this.state.image}
change to
, but on UPD. https://jsfiddle.net/69f71jbk/

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question