0

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

3
  • You want image source to change when you change the country in selectCountryChange? Commented May 8, 2020 at 10:23
  • yes i want image source to change when you change the country and also to pass img.src to state Commented May 8, 2020 at 10:33
  • Okay, I think a folk has posted a question that references what you just told me. See if it helps. Commented May 8, 2020 at 10:45

1 Answer 1

1

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;
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.