title: How to change image source using state variable with React.js
body: <p>I have an image component with the following html:</p>
  
  <pre><code>&lt;img src={this.state.img_path} onClick={this.getNew} alt={this.state.alt} width={150} /&gt; 
  </code></pre>
  
  <p>Initially I set the image to Blank which I import from an image:</p>
  
  <p>import Blank from './images/blank.jpg';</p>
  
  <p>then I use <code>Blank</code> to initialize my state variable.</p>
  
  <p>When the image is clicked, <code>getNew</code> is called, where I set the state variable <code>img_path</code> to a relative image path:</p>
  
  <pre><code>this.setState({img_path: item.ImgPath, alt: item.alt});
  </code></pre>
  
  <p>The function <code>getNew</code> gets called without an issue and executes without an error but the image does not get displayed, just an icon and <code>alt</code> value. How do i do dynamic image source switch in React?</p>
  
  <p>Update:</p>
  
  <p>here is my class</p>
  
  <pre><code>import React, { Component } from 'react';
  
  import Blank from './images/blank.jpg';
  
  
  
  class myImg extends Component {
  
  
      constructor(props) {
  
      super(props);
  
      this.state = {
  
          img_path: Blank,
  
          alt: 'blank',   
      };
  
  
      this.getNew = this.getNew.bind(this);
  }
  
  
  
  getNew() {
  
      const items = [{ItemName: 'test1', ItemImg: './images/test1.jpg'}, {ItemName: 'test2', ItemImg: './images/test2.jpg'} ];
  
      var item = items[math.floor(Math.random() * items.length)]; 
      this.setState({ img_path: item.ItemImg,
              alt: item.ItemName });
    }
  
   render() {
       return (&lt;div&gt;
              &lt;img src={this.state.img_path} onClick={this.getNew} alt={this.state.alt} width={150} /&gt;
  
          &lt;/div&gt;);
  
  }
  
  }
  
  export default myImg;
  </code></pre>