A simple Ajax request that processes data in React.js

It is new to respond, not 100% to how I should approach this relatively simple problem. I'm currently going to collect some images from Reddit that return these images to the "pImage" state.

Then these displayed images are displayed in the div 'content'. Normally, I would just go around this with a for loop, but is there a special way to handle it with a reaction?

componentDidMount: function() { var self = this; $.get(this.props.source, function(result) { var collection = result.data.children; if (this.isMounted()) { this.setState({ //Should I put a for loop in here? Or something else? pImage: collection.data.thumbnail }); } }.bind(this)); } 

Try showing my current status: https://jsfiddle.net/69z2wepo/2327/

+7
javascript reactjs
source share
1 answer

Here's how you could do it with the map function in the render method:

 var ImageCollect = React.createClass({ getInitialState: function() { return { pImage: [] }; }, componentDidMount: function() { var self = this; $.get(this.props.source, function(result) { var collection = result.data.children; if (this.isMounted()) { this.setState({ pImage: collection }); } }.bind(this)); }, render: function() { images = this.state.pImage || []; return ( <div> Images: {images.map(function(image){ return <img src={image.data.thumbnail}/> })} </div> ); } }); React.render( <ImageCollect source="https://www.reddit.com/r/pics/top/.json" />, document.getElementById('content') ); 

The fiddle works here: http://jsfiddle.net/2ftzw6xd/

+12
source share

All Articles