Home > OS >  How can I concatenate a string and variable into the name of another variable in React?
How can I concatenate a string and variable into the name of another variable in React?

Time:11-13

I am importing images and naming them img1, img2, img3 etc. I want to be able to increase the number on the name when I click a button, but when I concatenate or use template literals it returns a string.

Here for clarity:

import img1 from 'img1.jpg'
import img2 from 'img2.jpg'
import img3 from 'img3.jpg'

const [ num, setNum ] = useState(1)

function handleNextClick() {
    setNum(num   1)
}

This is where my problem is:

<img src={ 'img'   num} alt="" />

It returns as:

<img src='img1' alt="" />

I want:

<img src={img1} alt="" />

CodePudding user response:

You should store your images in a reference array, and pull from there:

import img1 from 'img1.jpg'
import img2 from 'img2.jpg'
import img3 from 'img3.jpg'

const images = [img1, img2, img3]

Then you can reference by index:

<img src={images[num - 1]} alt="" />

Note the - 1 to the num in order to use the zero index array.

CodePudding user response:

Hello in javascript you can do this by simply destructuring your values. and you can always access them by their index array indices usually start at 0

const x = [1, 2, 3, 4, 5];

so if you want to get the first value you do

x[0];

check out this page from MDN Web Docs to learn about destructuring assignments https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment

and this on arrays https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array

  • Related