2

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?

3 Answers 3

2

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.

Sign up to request clarification or add additional context in comments.

Comments

0

Create a variable:

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

Then access its fields

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

Comments

0

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}/>
  })
}

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.