React — delete list of components on button click

Daneesha Bartholomeusz
1 min readAug 13, 2019

--

Let’s say you hold the child components in a list. You can have it in the State.

inputList: []

Let’s say there’s a button on the parent component to add child components. Its code will look similar to this.

<div>
<Button variant= "light" className="button" onClick={this.onAddAnotherBtnClick}>
Add Another
</Button>
{this.state.inputList.map(function(input, index) {
return input;
})}
</div>

(You might have to bind the onAddAnotherBtnClick like this). In the state,

this.onAddAnotherBtnClick = this.onAddAnotherBtnClick.bind(this);

onAddAnotherBtnClick looks like this.

onAddAnotherBtnClick = (event) =>{
const inputList = this.state.inputList;
this.setState({
inputList: inputList.concat(<ChildComponent Id={inputList.length}
callbackDeleteButton={this.delete}/>)
});
}

This is the delete method.

delete = (Id) => {
delete this.state.inputList[Id];
this.setState({ inputList : this.state.inputList });
}

This is the Delete button on the child component.

<Button variant= "light" className="button" onClick={this.onDeleteButtonClick}>
Delete
</Button>

Here’s the onDeleteButtonClick method.

onDeleteButtonClick = () => {
this.props.callbackDeleteButton(this.state.Id);
}

(You’ll have to bind the method in the State like this).

this.onDeleteButtonClick = this.onDeleteButtonClick.bind(this);

What happens here is that I send the ID to each child component when it’s created on the props. When the child component’s delete button is clicked it sends its ID to the parent through a callback method the parent has supplied.

--

--

No responses yet