Reputation: 27
I've been looking around different answers but all of them are jQuery related or very complex for what I have in mind? I am working in a form and want that when user checks a box, its value should be added to an array storing info in the parent component. If box is unchecked, remove that item from array.
Code trimmed for simplicity
const Knowledge = (props) => {
const checkHandler = (e) => {
const tools = props.data.usesTools; //Array in parent component
const value = e.target.value; //Checkbox value
tools.includes(value) //If Array contains value
? tools.filter((tool) => tool.value != value) // Then remove item from Array
: tools.push(value) // Else, push item to Array;
};
return (
<div>
<label>
<input
type="checkBox"
name="usesTools"
value="Slack"
onChange={checkHandler}
/>
Slack
</label>
</div>
//Other checkboxes removed for simplicity
)
}
Questions:
1) How to add/remove items to Array if checkbox is selected/not selected.
2) I Tried adding a hook to check/uncheck the box but its checking all the boxes as soon the handler is called:
const [ isSelected, setSelected = useState(false);
<input
type="checkBox"
name="usesTools"
value="Slack"
onChange={checkHandler}
checked={isSelected}
/>
Upvotes: 0
Views: 3939
Reputation: 156
Whether you declare a component as a function or a class, it must never modify its own props. React is pretty flexible but it has a single strict rule: All React components must act like pure functions with respect to their props, as you are modifying props.data.usesTools
in the child component. what you need to do is to pass the callback function in Props to child component which will update the usesTools
Array, like below
## function to update the usesTools state in parent component ##
const [usesTools,setUsesTools]= React.useState([]);
const updateUsesTools = (item) => {
if (usesTools.includes(item)) {
setUsesTools(usesTools.filter(tool => tool.value != item));
} else {
setUsesTools([...usesTools, item]);// or push
}
};
## function in child component to handle change event ##
const checkHandler = e => {
const tools = props.data.usesTools; //Array in parent component
const value = e.target.value; //Checkbox value
props.updateUsesTools(value);
};
Upvotes: 4