Home > Enterprise >  Is there a way i can concatenate a string and variable into the name of another variable in react
Is there a way i can concatenate a string and variable into the name of another variable in react

Time:11-12

So 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