I have the following method as part of one of my components in a react app.
renderDeducs() { var deducArray=[]; for(var x =0;x<this.props.deducciones.length;x++) { var deduc = this.props.deducciones[x]; deducArray.push(<tr key={x}> <td key={x.toString()+"nombre"}>{deduc.nombre}</td> <td key={x.toString()+"porciento"}>{deduc.porciento}</td> <td><button onClick={(e) => {this.delete(deduc.nombre)}}>Borrar</button> | <button>Editar</button> </td> </tr> ); } console.log(deducArray); return deducArray; } The idea is to be able to display the items of an array and provide a delete button for each item. The items are displayed inside an HTML table. However, the button for each row is deleting the last item in the array (the last row of the table). Apparently, even though "deduc" is a local variable and should be out of scope when the click events fire, deduc seems to have the value used in the last iteration of the loop. How can I tell each button what item of the array I want to delete?
EDIT:
here is the code for the "delete" method of the component and the constructor:
constructor(props) { super(props); this.state = { addMethod : this.props.addMethod, delMethod : this.props.delMethod }; this.renderDeducs = this.renderDeducs.bind(this); this.delete = this.delete.bind(this); } delete(nombre) { alert("Deleting " + nombre); this.state.delMethod(nombre); } As you can see, the actual delete from the array method happens on a method that is bound to a component higher up in the component tree (that how you you achieve the "single source of truth", isn't it?) On the parent component, this is what that method looks like:
delDeduction(nombre) { var stateArray = this.state.deducciones; for (var x =0;x<stateArray.length;x++) { if(stateArray[x].nombre === nombre) { stateArray.splice(x,1); this.setState({deducciones:stateArray}); return; } } }
deletefunction? Your code looks fine here, not sure why it would be getting the wrong value.<td key={x.toString()+"nombre"}>{deduc.nombre}</td>render the right number?