phantom phantom - 2 months ago 19
React JSX Question

map images concatenating strings

I am using the

map
function to iterate over an array with images. I am then trying to display these images on the page.

You will see that the images are being concatenated into one stain. Does anyone know how to do this so i can show each individual image?

I have set up a jsfiddle here

Please see React code below:

var App = React.createClass({
render: function(){
var images = [
{
id:"1",
images:['https://i.scdn.co/image/dc284fcd7e581aa2b7ca56f28c7c74f0ca0ad393', 'https://i.scdn.co/image/97ffc63dd5abfe7203d8f5e90d1a74427ac756e7']
},
{
id:"2",
images:['https://i.scdn.co/image/97ffc63dd5abfe7203d8f5e90d1a74427ac756e7', 'https://i.scdn.co/image/97ffc63dd5abfe7203d8f5e90d1a74427ac756e7']
}
];
return(<List images={images} />)
}
});

var List = React.createClass({
render: function() {
var images = this.props.images.map(function(image){
return(image.images[0]); // updated here
})
return(
<div>
<img src={images}></img>
<p>{images}</p>
</div>
)
}
});

ReactDOM.render(
<App name="World" />,
document.getElementById('container')
);

Answer

Does the following work? https://jsfiddle.net/petebere/19fmn5qs/

The change was to add the <img /> tag with the src attribute set to the url:

        var images = this.props.images.map(function(image, index){
            return <img key={index} src={(image.images[0])} />;
        });

Also, you now don't need the <img /> tag in your final return statement. Please see my updated fiddle. I've also added the key attribute as required in the React docs: https://facebook.github.io/react/docs/multiple-components.html#dynamic-children

Full code:

var App = React.createClass({
    render: function() {
      var images = [
         {
            id:"1",
            images:['https://i.scdn.co/image/dc284fcd7e581aa2b7ca56f28c7c74f0ca0ad393', 'https://i.scdn.co/image/97ffc63dd5abfe7203d8f5e90d1a74427ac756e7']
         },
         {
            id:"2",
            images:['https://i.scdn.co/image/97ffc63dd5abfe7203d8f5e90d1a74427ac756e7', 'https://i.scdn.co/image/97ffc63dd5abfe7203d8f5e90d1a74427ac756e7']
         }
      ];

     return(<List images={images} />);
   }
});

var List = React.createClass({
    render: function() {
        var images = this.props.images.map(function(image, index){
            return <img key={index} src={(image.images[0])} />;
        });
        return(
            <div>
                <p>Your images</p>
                {images}              
            </div>
        );       
    }
});

ReactDOM.render(
  <App name="World" />,
  document.getElementById('container')
);
Comments