How to render images with React JS using map or loop?
You can use the js map
function combined with ES 6 template literals.
class Stopka extends Component {
render() {
const array = ["wood", "lake", "sun", "moon", "sea"];
const images = array.map(image => {
return <img key={image} src={require(`./icons/${image}.png`)} className="img-responsive" />
});
return (
<div className="container">
<footer className="row">
<div className="col-xs-12 col-sm-6 col-md-6 col-lg-6">
<h4>Some text</h4>
</div>
<div className="col-xs-12 col-sm-6 col-md-6 col-lg-6">
{ images }
</div>
</footer>
</div>
);
}
}
export default Stopka;
For others who had the same problem as me. This is working example as well. In my opinion with key index is better, cuz it not produce errors in console. Great for bigger projects.
import React, { Component } from 'react';
import './Stopka.css';
class Stopka extends Component {
render() {
let names = ['wood', 'sun', 'moon', 'sea'].map( (name, index) => {
return <img key={index} className="img-responsive" alt="" src={require(`./icons/${name}.png`)} />
} );
return (
<div className="container">
<footer className="row">
<div className="col-xs-12 col-sm-6 col-md-6 col-lg-6">
<h4>some text</h4>
</div>
<div className="col-xs-12 col-sm-6 col-md-6 col-lg-6">
{ names }
</div>
</footer>
</div>
);
}
}
export default Stopka;
Thanks to Paul Fitzgerald for the guide.