Alex Alex -4 years ago 73
React JSX Question

ReactJS Load Images on Click

Hello im trying to make an image changer. at first load i should get displayed the first image in the state. if click on the button the image should be changed to second and so on. the problem right now is get displayed both images with buttons

here is my bin : enter link description here

Answer Source

Because you display the 2 image in your renderer.

Heres an idea how to do it (with no animation, I dont know the CSSTransitionGroup component). Just replace your main.js code withthe following

import React from 'react'
import {render} from 'react-dom'
import { CSSTransitionGroup } from 'react-transition-group'

class FadeImage extends React.Component {

  constructor(props) {
    this.state = {
      images: [
      currentImage: 0

  fadeImage(e) {
    this.setState({currentImage: (this.state.currentImage + 1) % this.state.images.length})

  render() {
    return (
            <div className="image">
            <button className="button" onClick={this.fadeImage.bind(this)}>Click!</button>
            <img src={this.state.images[this.state.currentImage]}/></section>

render(<FadeImage />, document.querySelector('#app'))
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download