Search code examples
reactjssetstatereact-state-managementimgsource

how to add image src to react state and setstate


I'm making an application that necessarily demand to pass a handleChange on <img/> tag in react to store the image.src on to the state

 import React, { Component } from 'react'  
export class App extends Component {  
 render() {  
        const selectCountryChange = () => {  
            const img = document.querySelector('#img-country');  
            const select = document.querySelector('#country');  
            img.src = \`https://flagpedia.net/data/flags/h80/${select.selectedOptions\[0\].dataset.countrycode.toLowerCase()}.webp\`;  
        };  
        return (  
 <div>  
 <select id="country">  
 <option data-countryCode="IN" value="91">India</option>  
 <option data-countryCode="US" value="1">US</option>  
 <option data-countryCode="GB" value="44">UK</option>  
 </select>  


 <div class="image">  
 <img src="" id="img-change">  
          </div>  
            </div>  
        )  
    }  
}  
export default App

can anyone please tell me how to add state management to react for img.src


Solution

  • You can use the onChange event of the select to change the state of the component when a country is selected.

    export class App extends Component {  
      state={
        imageSrc:'',
        imageAlt:''
      }
    
      handleChange(e){
        const countryCode=e.target.getAttribute('data-countryCode').toLowerCase()
        this.setState({
          imageSrc:'https://flagpedia.net/data/flags/h80/'+countryCode+'.webp',
          imageAlt:countryCode
        })
      }
    
      render() {  
             return (  
      <div>  
        <select id="country" onChange={this.handleChange}>  
          <option data-countryCode="IN" value="91">India</option>  
          <option data-countryCode="US" value="1">US</option>  
          <option data-countryCode="GB" value="44">UK</option>  
        </select>  
    
    
          <div class="image">  
            <img src={this.state.imageSrc} id="img-change" alt={this.state.imageAlt}/>  
          </div>  
      </div>  
             )  
         }  
     }  
    
    export default App;