vuvu vuvu - 18 days ago 5
React JSX Question

How to get array values in react js

I want to get the updated values of an array. When I do a console.log I only get the length of the array and the new values aren't shown in the view. What is wrong here? js fiddle

react js

getInitialState: function() {
return {
owner: "Martin Schwatz",
friends: ["Pietro", "Mike", "Shawn", "Bilbo"],
}
},
updateFriends: function(friend) {
var a = this.state.friends.push(friend);
console.log(a);
this.setState({
friends: a,
});
},

Answer

Take a look at this one

var Hello = React.createClass({
  getInitialState: function() {
    return {
      owner: "Martin Schwatz",
      friends:  ["Pietro", "Mike", "Shawn", "Bilbo"],
    }
  },
  updateFriends: function(friend) {
    var newFriends = this.state.friends.concat(friend)
    this.setState({
      friends: newFriends,
    });
  },
  click: function(){
    this.updateFriends('VuVu')
  },
  render: function(){
    var listOfFriends = this.state.friends.map(function(item,i){
        return <li key={i}>{item}</li>
    }.bind(this))
    return <div>
        <button onClick={this.click}>Add VuVu</button>
        <hr/>
      {listOfFriends}
    </div>
  }
});

ReactDOM.render(
  <Hello />,
  document.getElementById('container')
);

It should work for you <fiddle>

Comments