Mahmud Adam Mahmud Adam - 5 months ago 9
Javascript Question

Rendering button inside a list

How would one go about rendering a button with a click event inside of a list? I am not sure why I cannot render a button next to each dog in the list and add that dog to my cart array. I know I am missing something here because whenever I add a function to an

onClick
event I must get an error because my entire interface disappears. Say I have a component:

var PetStore = React.createClass({
getInitalState: function() {
return ({
cart: []
})
},
addToCart: function(dog) {
this.setState({
cart: this.state.cart.concat([dog])
})
},
render: function() {
return (
<ul>
{this.props.dogs.map(function(dog){
return <li>Breed: {dog.breed}, age: {dog.age}
<button onClick={this.addToCart}>Buy</button></li>
})}
</ul>
)

}
})

Answer
    var DOGS = [{
  breed: 'Husky',
  age: 5
}, {
  breed: 'Pit bull',
  age: 2
}, {
  breed: 'Golden Retriever',
  age: 10
}, {
  breed: 'Black lab',
  age: 2
}]
var PetStore = React.createClass({
  propTypes: {
    dogs: React.PropTypes.array
  },
  getInitialState: function() {
    return ({
      cart: []
    })
  },
  addToCart: function(dog) {
    this.setState({
      cart: this.state.cart.concat([dog])
    })
  },
  render: function() {
console.log(this.props);
    var self = this;
    return (
      <ul>
        {this.props.dogs.map(function(dog, index){
          return (<li key={index}>Breed: {dog.breed}, age: {dog.age} <button onClick={self.addToCart.bind(self,dog)}>Buy</button></li>)
    })}
      </ul>
    )

  }
})

ReactDOM.render(<PetStore dogs={DOGS}/>, document.getElementById('test'));