I have a component ‘CheckboxGroup’ which has an onChange() function called when a checkbox is clicked. How can I update the state for ‘selectedValues’ during this call to onChange()?
export const CheckboxWindow: React.FC<Props> = props => {
const [selectedValues, setSelectedValues] = React.useState<string[]>([]);
return (
<Window>
<CheckboxGroup
onChange={(checked, value) => {
if (checked && !selectedValues.includes(value)) {
this.setState({
selectedValues: [...this.state.selectedValues, value],
});
} else if (!checked && selectedValues.includes(value)) {
setSelectedValues(selectedValues.filter(val => val != value));
}
}}
/>
</Window>
);
};
I am getting the error:
Object is possibly ‘undefined’
for ‘this.setState’ and ‘this.state’.
setSelectedValues in the else if seems to compile fine however.
2
Answers
This is the function component, without setState and this.
You are mixing class and function components. Since you are using a functional component, you should not be using the
this
keyword, or thesetState
function. In fact, the second item in the array returned fromuseState
is how you will update state in a functional component: