Alex Alex -3 years ago 45
Javascript Question

ReactJS How to add additional image To props and change them on Click

Hello im trying to add an second image to my image props and change them on click any suggestions how can i solve it? here is my bin
my react bin

Answer Source

Below is an example of how you can do this.

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

class FadeImage extends React.Component 
{
  constructor(props, context, images) 
  {
     super(props);

     this.state = {
       index: 0,
       imageClass: 'image'
     };

     this.fadeImage = this.fadeImage.bind(this);
  }

  fadeImage(e) 
  {
     e.preventDefault();

     var s = {
       index: (this.state.index + 1) % this.props.images.length
     };

     if (this.state.imageClass === 'image') 
     {
       s.imageClass = "image-loaded";
     } 
     else
     {
       s.imageClass = "image";
     }

     this.setState(s);

     console.log('clicked');
  }

  render() 
  {
     return (
       <div>
         <a href="#" onClick={this.fadeImage}>Change Me!</a>
         <img src={this.props.images[this.state.index]} />
       </div>
     )
  }
}

render(<FadeImage images={['http://via.placeholder.com/350x150', 'http://via.placeholder.com/350x151']} />, document.querySelector('#app'))

Note that its perfectly fine to keep image paths in props. But you do need to have a current image index in state. Also there is no need to call setState multiple times. You can prepare your updates as part of one object and introduce all of them at once.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download