How to add chips value in an array in ReactJs

Ankit Kumar Rajpoot
2 min readAug 28, 2020

--

Chips Example

Chips are compact elements that represent an input, attribute, or action.

An example of rendering multiple Chips from an array of values. Deleting a chip removes it from the array. Note that since no onClick property is defined, the Chip can be focused, but does not gain depth while clicked or touched.

There are some basic steps to implement chips in ReactJs.

Step 1:- Install “material-ui-chip-input” through the following command.

$ npm i --save material-ui-chip-input@next

Step 2:- Import “material-ui-chip-input” in your component file.

import ChipInput from "material-ui-chip-input";

Step 3:- Define state

constructor(props) {
super(props);
this.state = {
tags: []
};

Step 4:- Define functions for adding and deleting chips

// Add Chips
handleAddChip = (chip) => {
this.setState({
tags: [...this.state.tags, chip]
});
}
// Delete Chips
handleDeleteChip = (chip) => {
this.setState({
tags: _.without(this.state.tags, chip)
});
}

In this function, I am using the underscore library for delete value from the array you can use any other or basic javascript function.

Step 5:- Use ChipInput in the component

<ChipInput
label="Video Tags"
value={this.state.tags}
onAdd={(chip) => this.handleAddChip(chip)}
onDelete={(chip, index) => this.handleDeleteChip(chip, index)}
/>

Example:-

Demo
Inspect State

That’s it for this time! I hope you enjoyed this post. As always, I welcome questions, notes, comments and requests for posts on topics you’d like to read. See you next time! Happy Coding !!!!!!

--

--

Ankit Kumar Rajpoot
Ankit Kumar Rajpoot

Written by Ankit Kumar Rajpoot

I’m a MERN Developer. ( Redux | AWS | Python ) I enjoy taking on new things, building skills, and sharing what I’ve learned.

No responses yet