so i am new to React JS and i am trying to create new groups and rows onClick of a button. So i have an array named groups
which gives me the Parent component and then another array named rows
which loops and gives the Row component. I have 2 methods, addRow
and addGroup
to add a new Parent component and row component dynamically. But everytime i add or delete a row, it seems to add and delete from all the groups.How can i keep every group and row separate from each other?
This is what my App.js file looks like:-
import React, {Component} from 'react';
import './App.css';
import Parent from './Parent.js'
class App extends Component {
state = {
rows: [
{id:0,value: 'row1', options:[1,2,3,4,5] }
],
groups : [
{ id:0, title: 'New Group' }
],
}
updateValue = (e, idx) => {
const rows = [...this.state.rows];
rows[idx].value = e.target.value;
this.setState({
rows,
});
}
addNewGroup = () => {
const groups = [...this.state.groups, { id:this.state.groups.length, title: 'New Group'}]
this.setState({
groups
})
}
addRow = () => {
const rows = [...this.state.rows, {id: this.state.rows.length ,value:'',options: []}];
this.setState({
rows,
});
}
deleteRow = (item) => {
let filtered = this.state.rows.filter(row => row.id !== item.id);
this.setState ({
rows: filtered
})
}
render() {
return (
<div className = "App">
{
this.state.groups.map ( (group,idx) => {
return (
<Parent
key = {idx}
title = {group.title }
rows = { this.state.rows }
deleteRow = {this.deleteRow.bind(this) }/>
)
})
}
<button onClick = {this.addRow}> Add </button>
<button onClick = {this.addNewGroup }>Add Group </button>
</div>
)
}
}
export default App;
This is what my parent component looks like:-
import React from 'react'
import Row from './Row.js'
const Parent = (props) => {
return (
<div>
<h4>{ props.title }</h4>
{
props.rows.map( (row,idx) => {
return (
<Row
key = {idx}
index = {idx}
value = { row.value }
options = { row.options }
delete = { () => { props.deleteRow(row) } }/>
)
})
}
</div>
)
}
export default Parent;
This is my Row component:-
import React from 'react'
import './Row.css'
const Row = ( props) => {
let options = props.options.map(opt => <option key={opt}>{opt}</option>);
return (
<div>
<input></input>
<select>
{options}
</select>
<button onClick = { () => { props.delete(props.index); } } > Delete </button>
</div>
)
}
export default Row
So basically addGroup should give me a new group and i should be able to add and delete rows individually without affecting the rows in the other group. Thank you.