skip to Main Content

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


  1. This is the function component, without setState and this.

    Login or Signup to reply.
  2. 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])
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search