1

I am trying to generate a list of components for a form

How can I access the individual checkbox states and names?

const Schemas = () => { 
    const [inputs, setInputs] = useState({});
    const [ isChecked, setChecked ] = useState( true );

    const handleChange = (event) => {
        console.log(event) //gives only true or false
        const name = event.target.name; //undefined
        const value = event.target.value; //undefined
        setInputs(values => ({...values, [name]: value}))
    }
    return(
        <VStack>
            <form>
                {schemas.map((element, index) => {
                    {console.table(element)}
                    return(
                        <CheckboxControl
                            key={index}
                            checked={isChecked}
                            label={element.title}
                            help={element.description}
                            name={element.name}
                            onChange={ handleChange }
                        />
                    )
                })}
            </form>
        </VStack>
    );
};

1 Answer 1

1

Rather than passing handleChange directly to onChange, you can use an anonymous function to call it:

<CheckboxControl
    key={index}
    checked={isChecked}
    label={element.title}
    help={element.description}
    name={element.name}
    onChange={(value) => { 
        handleChange(element.name, value);
    }}
/>

Then your handleChange function can accept the name and value as its parameters.

const handleChange = (name, value) => {
    setInputs(values => ({...values, [name]: value}));
};
1
  • ok, it seems the onChange in the component still only passes the value, so I've modified it as onChange={(value) =>{ handleChange(element.name, value); }} Dec 30, 2022 at 20:01

Not the answer you're looking for? Browse other questions tagged or ask your own question.