1

I am trying to hit a URL based on some variable data.

{
  this.state.countries.map((country, key) => {
    return <a key={country.iso2}>
      <img src="https://www.countryflags.io/{country.iso2}/shiny/24.png" />
    </a>;
  });
}

The value {country.iso2} in the above URL is dynamic. Please help me to format the URL correctly.

5 Answers 5

3

Try Template literals. Note use of back tick and $

<img src=`https://www.countryflags.io/${country.iso2}/shiny/24.png`/>
Sign up to request clarification or add additional context in comments.

Comments

2

As you're working with jsx, you'll have to add the curly braces, then template literals and then the variable surrounded by ${}, like so:

let country = { iso2: "au" };
ReactDOM.render(
  <img src={`https://www.countryflags.io/${country.iso2}/shiny/24.png`} />,
  root
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
<div id="root"></div>

Comments

0

you can do it like

{this.state.countries.map((country, key) => {
       return
           <a key={country.iso2}>
               <img src=`https://www.countryflags.io/${country.iso2}/shiny/24.png`/>
                                </a>
 })}

Comments

0

Use the backtick and dollar sign

{this.state.countries.map((country, key) => {
                            return
                                <a key={country.iso2}>
                                <img src=`https://www.countryflags.io/${country.iso2}/shiny/24.png`/>
                                </a>
 })}

Comments

0

Correct way of doing is using Template literals

If your value is dynamic then use of back tick and $

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.