Home > database >  How do I declare a variable in JSX?
How do I declare a variable in JSX?

Time:04-20

I have the below code that gets data from an Apollo Server backend. the data comes in the format:

{ name: 'geodude', url: 'https://pokeapi.co/api/v2/pokemon/74/' },
{ name: 'graveler', url: 'https://pokeapi.co/api/v2/pokemon/75/' },

To display the image I have the split this url string and get the id in the end like 74 or 75. But how do I split this in JSX as it does not allow me to declare any variables.

return (
    <div className="App">
      {data.pokemonList.map((data) => (
         let a = data.url.split(/) // this gets the id from my url
         const b = "https://raw/${a}.png";    //use it in the string like this

But obviously I can't do this in JSX. Also I can't do this outside the return because I have to split like this for all the mapped values. Is there an easier way to do this?

CodePudding user response:

Sure you can do it inside JSX - you can either put it all into one expression, eg:

{data.pokemonList.map((data) =>
  <img src={
    `https://raw/${data.url.match(/\d (?=\/$)/)[0]}.png`
  }>
)}

Or create a block, allowing you to declare variables, then return JSX at the end:

{data.pokemonList.map((data) => {
  const num = data.url.match(/\d (?=\/$)/)[0];
  const url = `https://raw/${num}.png`
  return <img src={src}>;
})}

Note that you need backticks in order to interpolate into a string with ${} (not "), and that your current a will give you an array, not a string, so interpolating with ${a} won't work. You need to extract the string you want from the URL.

  • Related