Using a Set data structure in React’s state. Since react will identify state changes only if the state property was replaced, and not mutated (shallow compare), you’ll have to create a new Set from the old one, and apply the changes to it.
Here is an example which you can use it in your class:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 | export default class Checklist extends React.Component { constructor(props) { super(props); this.state = { checkedItems: new Set() } this.addItem = this.addItem.bind(this); this.removeItem = this.removeItem.bind(this); } addItem(item) { this.setState(({ checkedItems }) => ({ checkedItems: new Set(checkedItems).add(item) })); } removeItem(item) { this.setState(({ checkedItems }) => { const newChecked = new Set(checkedItems); newChecked.delete(item); return { checkedItems: newChecked }; }); } getItemCheckedStatus(item) { return this.state.checkedItems.has(item); } // More code... } |
If you like this question & answer and want to contribute, then write your question & answer and email to freewebmentor[@]gmail.com. Your question and answer will appear on FreeWebMentor.com and help other developers.