domantasjurkus
domantasjurkus

Reputation: 69

React - Trying to Changing <img> src attribute

I'm trying to change the src attribute of an element after an AJAX call to a database. I have a default image url defined in getDefaultProps(), but after the AJAX call the image doesn't change.

PictureWidget is a child component of a Section component that controls the state (it also passes dataSource and dataSourceParams to PictureWidget). I'm not sure if I can use a local state for PictureWidget so I'm trying to do it through props.

This is my code:

var PictureWidget = React.createClass({

getDefaultProps: function() {
  return {
    url: 'https://d2o57arp16h0eu.cloudfront.net/echo/img/no_image_available.png'
  }
},

componentDidMount: function() {
  this.componentDidUpdate();
},

componentDidUpdate: function() {

  // Grab img URL from DB
  var postData = {
    dataSource: this.props.params.dataSource,
    dataSourceParams: this.props.dataSourceParams
  };

  $.ajax({
    type: 'POST',
    url: ajax_endpoint,
    cache: false,
    data: postData,
    dataType: 'json',
    success: function(response) {
      if (response.data.length > 0) {
        this.updateImage(response.data[0][0]);
      }
    }.bind(this),
    error: function(response) {
      this.render();
    }
  });

},

updateImage: function(url) {
  console.log("Updating props.url with " + url);
  this.props.url = url;
  this.render();
},

render: function(imageURL) {
  console.log("Rendering img " + this.props.url);

  return React.createElement('div', {className: ' pure-u-' + this.props.columns},
    React.createElement('div', {className: 'picture-widget'},
      React.createElement('img', {src: this.props.url})
    )
  )
}
});

And this is my console log (forgive me for the poor formatting, still new to Overflow):

Rendering img https://d2o57arp16h0eu.cloudfront.net/echo/img/no_image_available.png
Updating props.url with http://vignette3.wikia.nocookie.net/animalcrossing/images/4/49/Tumblr_lvrcmvCpsS1qbeyouo1_500.jpg/revision/latest
Rendering img http://vignette3.wikia.nocookie.net/animalcrossing/images/4/49/Tumblr_lvrcmvCpsS1qbeyouo1_500.jpg/revision/latest

The initial render() grabs the default URL, but after the AJAX call this.props.url does get updated to the new value, so I would suspect React.createElement('img', {src: this.props.url}) is the trouble maker. Can I not update the src attribute this way?

Upvotes: 3

Views: 11101

Answers (1)

Chris Schmitz
Chris Schmitz

Reputation: 8257

This is what state is for. Try using getInitialState instead of getDefaultProps and bind url to this.state using setState().

getInitialState: function() {
  return {
    url: 'https://d2o57arp16h0eu.cloudfront.net/echo/img/no_image_available.png'
  };
},

updateImage: function(url) {
  console.log("Updating state.url with " + url);
  this.setState({ url: url });
}

Upvotes: 2

Related Questions