0

I am trying to show a series of pictures but the following code does not replace {i}with the actual number. It renders:

<div>
  <img src='/img/picture{i}.jpg' />
  <img src='/img/picture{i}.jpg' />
</div>

This is the code.

class Pictures extends Component {
  render () {

    return (
      <div>
        {Array.from({length: 2}, (_, i) => (
          <img src='/img/picture{i}.jpg' />
        ))}
      </div>
    )
  }
}
Hedge
  • 16,142
  • 42
  • 141
  • 246
  • Possible duplicate of [Reactjs - Images not displaying](https://stackoverflow.com/questions/45334874/reactjs-images-not-displaying) – Shubham Khatri Aug 08 '17 at 17:41

1 Answers1

5

This should work (with ES6 template literals syntax):

<img key={i} src={`/img/picture${i}.jpg`} />

Alternatively, you can use String concatenation syntax:

<img key={i} src={'/img/picture' + i + '.jpg'} />
Denialos
  • 956
  • 7
  • 16
  • and don't forget `key` : https://facebook.github.io/react/docs/lists-and-keys.html – Hitmands Aug 08 '17 at 16:46
  • Note, tho: https://medium.com/@robinpokorny/index-as-a-key-is-an-anti-pattern-e0349aece318 – Andy Aug 08 '17 at 16:52
  • @Andy: I know that, but in the practical sense, I never had an issue with an index being used as a key (of course, my experience may depend on app-specific things like component tree hierarchy, dependencies, etc.). Not sure about others' experiences. – Denialos Aug 08 '17 at 16:53