React - trying to change the <img> src attribute

I am trying to change the src attribute of an element after an AJAX call to the database. I have a default image url defined in getDefaultProps()

, but after an AJAX call, the image doesn't change.

PictureWidget

is a child of the component Section

that manages the state (it also passes dataSource and dataSourceParams to PictureWidget

). I'm not sure if I can use local state for PictureWidget

, so I'm trying to do this via 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 (pardon me for the bad 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 one render()

grabs the default url, but after the AJAX call is this.props.url

updated to the new value, so I suspect that React.createElement('img', {src: this.props.url})

is the originator of the problem. Can I not update the src attribute this way?

+3


source to share


1 answer


This is what the state is for. Try using getInitialState

instead getDefaultProps

and bind url

to this.state

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

      

+1


source







All Articles