Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Simple Ajax request, that loops over data in React.js

New to react and not 100% on how I should approach this relatively simple problem. I'm currently looking to gather some images from Reddit, that push those images back to the 'pImage' state.

Then have those said images display within the 'content' div. Usually, I would just go about this with a for loop, but is there a special way I should be processing it with react?

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

Fiddle to show my current state: https://jsfiddle.net/69z2wepo/2327/

like image 650
Starboy Avatar asked Feb 13 '15 16:02

Starboy


1 Answers

Here is how you would do it with a 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')
    );

Here is working fiddle: http://jsfiddle.net/2ftzw6xd/

like image 167
nilgun Avatar answered Sep 22 '22 06:09

nilgun