Search code examples
javascriptreactjstypescriptcomponentssetstate

How to properly set component state during onChange call in React Typescript


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.


Solution

  • You are mixing class and function components. Since you are using a functional component, you should not be using the this keyword, or the setState function. In fact, the second item in the array returned from useState is how you will update state in a functional component:

    if (checked && !selectedValues.includes(value)) {
        setSelectedValues(prev => [...prev, value])
    }