Jessie Campbell Jessie Campbell - 1 month ago 7
React JSX Question

pass index from function to function in react

I have a list of item, and upon on click of the delete button the item will get removed. I know the steps to do it but I'm stuck on how can I pass the key to the dlt_item scope.

http://jsfiddle.net/3Ley7uac/1/

var App = React.createClass({
getInitialState(){
return {
items:[1,2,3]
}
},
dlt_item(key){
//how to get index/id here?
},
renderItem(){
return this.state.items.map((item,i)=> <li key={i}>{item}
&nbsp;
<button>Edit</button>
<button onClick={this.dlt_item}>Delete</button>
</li>
)
},
render(){
return(
<ul>
{this.renderItem()}
</ul>
)
}
})

Answer

You need to bind this.dlt_item as

<button onClick={this.dlt_item.bind(this, i)}>Delete</button>

and in your dlt_item function you can splice your state array from this index passed.

Code

var App = React.createClass({
   getInitialState(){
   return {
     items:[1,2,3]
   }
   },
   dlt_item(key){
   console.log(key);
   this.state.items.splice(key, 1);
   this.setState({items: this.state.items});
   //how to get index/id here and do setState
   },
   renderItem(){
   return this.state.items.map((item,i)=> <li key={i}>{item}
   &nbsp;
   <button>Edit</button> 
   <button onClick={this.dlt_item.bind(this, i)}>Delete</button>
   </li>
   )
   },
   render(){
      return(
      <ul>
        {this.renderItem()}
      </ul>
      )
   }
})

React.render(<App />, document.getElementById('container'));

JSFIDDLE

Instead of splice you can use filter as

dlt_item(key){
   var items = this.state.items.filter(function(obj){
    return obj != (key + 1);


   });
   console.log(items);
   this.setState({items: items});
   //how to get index/id here and do setState
   },

JSFIDDLE

Comments