0

This is a standard working checkbox:

const [myValue1, setMyValue1] = React.useState(true);

<InputCheckbox
 label="Registry"
 value={myValue1}
 onChange={(value, name) => {
 setMyValue1(value);
 console.log(`${name}:${value}`);}}
/>

Now I create a lot of checkboxes like this:

{someTools.map(({ title }) => (
    <>

    <InputCheckbox
     label={title}
     value={false} <- Current Placeholder
     onChange={(value, name) => { ...? }}
    />

))}

As you can see, in the current state, I can not check or uncheck my checkboxes because I am missing the const [myValue / setMyValue1] for every checkbox in my .map function.

How can I dynamically create those variables and use them in my onChange function?

1 Answer 1

1

Assuming each tool's title is unique, i'd store the checked values in an object like this:

{ [title]: <isChecked> }

Further assuming that we already know tools when rendering (we don't fetch them in this function), the useState call could look like this:

const [checked, setChecked] = React.useState(
    Object.fromEntries(someTools.map(({title}) => [title, false]))
);

false being the initial checked value. (If you fetch the tools in this component, you should initialize useState with {})

Last but not least, the JSX would look like this:

someTools.map(({title}) => 
    <InputCheckbox
        key={title}
        label={title}
        value={checked[title]}
        onChange={() => setChecked({...checked, [title]: !checked[title]})}
    />
)
Sign up to request clarification or add additional context in comments.

1 Comment

thank you kenny. you helped me so much. makes sense!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.