SkyeBoniwell
SkyeBoniwell

Reputation: 7122

Select All checkbox not behaving as expected

I'm trying to write this custom React component for my main Formik react form.

I want to create a 'select All' checkbox that, when selected or unselected, selects or deselects all the other checkboxes.

I got it to recognize that I'm clicking the 'Select All' checkbox using the onChange event.

But when I do this, it always stays selected.

I am also not sure how to automatically select and deselect the other checkboxes.

Another thing is, this component doesn't use state because state is handled by Formik in my my form page. Formik just looks for which checkbox is checked and adds it to state.

Is there a way to do this?

Thanks!

Here is my code:

const EngineList = () => {

    const handleEngineChange = (e) => {
        console.log('set engines to All -- ', e);
    } 

    return (
        <>

            <label>
                <Field type="checkbox" name="engines" onChange={handleEngineChange} value="1" selected />
                Select All
            </label>
            <label>
                <Field type="checkbox" name="engines" value="2" />
                Formula One
            </label>
            <label>
                <Field type="checkbox" name="engines" value="3" />
                Nascar
            </label>
        </>
    );  
}

export default EngineList;

Upvotes: 3

Views: 2583

Answers (1)

rrebase
rrebase

Reputation: 4219

Since Formik handles state, you have to use the API to change state. There's setFieldValue, which you can use.

Upvotes: 2

Related Questions