Reputation: 1368
I have a Row Component that i am importing into my App.js component and apparently i but the delete function doesn't seem to be deleting the correct row. Even if i delete the second one, it deletes the last one first. So basically if i click delete on second row, it should delete the second one not the third etc.
My App.js or my root component looks like this: -
import React, {Component} from 'react';
import './App.css';
import Row from './Row.js'
class App extends Component {
state = {
rows: [
{value: 'row1', options:[1,2,3,4,5] },
{value: 'row2', options:[1,2,3,4,5] },
{value: 'row3', options:[ 1,2,3,4,5 ]}
]
}
updateValue = (e, idx) => {
const rows = [...this.state.rows];
rows[idx].value = e.target.value;
this.setState({
rows,
});
}
addRow = () => {
const rows = [...this.state.rows, {value:'', options: [1,2,3,4,5}];
this.setState({
rows,
});
}
deleteRow = (idx) => {
const copy = [...this.state.rows]
copy.splice(idx,1)
this.setState ({
rows:copy
})
}
render() {
return (
<div>
{
this.state.rows.map ( (row,idx) => {
return (
<Row
key = {idx}
value = { row.value }
onChange = { (e) => this.updateValue(e,idx) }
delete = { this.deleteRow.bind(this,idx) } />
)
})
}
<button onClick = {this.addRow}> Add </button>
</div>
)
}
}
export default App;
And my row component looks like this:-
const Row = ( props) => {
let options = props.options.map(opt => <option key={opt}>{opt}</option>);
return (
<div>
<input value= { props.value } onChange={ props.onChange }></input>
<select>
{options}
</select>
<button onClick = { props.delete} > Delete </button>
</div>
)
}
export default Row
I asked a similar question yesterday link but didn't realize at the time that the items weren't being deleted from the right position?
Upvotes: 0
Views: 139
Reputation: 9779
Try this
deleteRow = (item) => {
let filtered = this.state.rows.filter(row=>row.value!==item.value);
this.setState ({
rows: filtered
})
}
pass row to your delete function
<Row
key = {idx}
value = { row.value }
onChange = { (e) => this.updateValue(e,idx) }
delete = {()=>this.deleteRow(row) } />
)
if every row(object) is having unique id then use that id instead of value like-
let filtered = this.state.rows.filter(row=>row.id!==item.id);
Upvotes: 1