Birmjin In
Birmjin In

Reputation: 129

How to make use of variable name using array of string in React.js

What I'm trying to do is removal of duplicate codes like below.

import icon1 from './images/abc.png'
import icon2 from './images/xyz.png'
import icon3 from './images/pqr.png'
import icon4 from './images/stu.png'
...

<img src={icon1}/>
<img src={icon2}/>
<img src={icon3}/>
<img src={icon4}/>
...

I want to rewrite above code using loop or map function like below conceptually.

let array = [1,2,3,4];

{array.map( v =>
  <img src={icon + v} />
);}

Sure, it does not work. In using React.js, how can I make use of variable using string concatenation?

Upvotes: 2

Views: 810

Answers (3)

Mayank Shukla
Mayank Shukla

Reputation: 104529

Not sure about the best solution, but this one will work.


Instead of storing 1,2,3,4 in an array, store the image names like this:

let imgArr = ['abc', 'xyz', 'stu'];

When use require:

{
    imgArr.map(v =>
        <img src={require(`./images/${v}.png`)} />
    );
}

Note: No need to import all the images at the top, if you are using this.

Upvotes: 2

Umesh
Umesh

Reputation: 2742

You can certainly do it

const icons = [ { id: 1, src: './images/abc.png'},
{ id: 2, src: './images/def.png'} ]  // add more 

{ icons.map( (item) => { 
    <img key={item.id} src={item.src}/>
  })
}

Upvotes: 0

Ji aSH
Ji aSH

Reputation: 3457

Create a variable:

let ICONS = {
    1: icon1,
    2: icon2,
    3: icon3,
    4: icon4
}

Then access its fields

{array.map( v =>
    <img src={ICONS[v]} />
);}

Upvotes: 0

Related Questions