How to correctly implement Checkboxes and Radios? #134
-
Hello Ivan, I'm loving using Formiz after coming from Formik - it's really refreshingly nice to use. I can't seem to get checkboxes and radio inputs to work correctly though. I've done these in Formik, but I'm not sure of the correct way to make them in Formiz. As far as I understand, checkboxes and radios are both basically the same component, just with a different 'type' and with Radios being needed to be wrapped in a fieldset or div with role='group'. Here is an example of my checkbox component. Formiz collects the data correctly from it - though only after it has been clicked. e.g. if it has been clicked checkboxName: true, and if I deselect it after selecting it, checkboxName: false, but it doesn't default to a false value, so if I console.log(values) without having clicked on the checkbox, checkboxName will not output in the log.
I've basically adapted the code from your answer here, but I've got something wrong. Can you see what I', doing wrong, please? Many thanks for any help, |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments 1 reply
-
Hi @MattHeslington You can pass a const Checkbox = (props) => {
const { errorMessage, isValid, value, setValue } = useField({
...props,
defaultValue: props.defaultValue ?? false // Update here
});
const { title, required, name, style, ...otherProps } = props
const showError = !isValid
return (
<div>
<input
id={name}
type='checkbox'
checked={value}
required={required}
onClick={() => setValue(!value)}
{...otherProps}
/>
<label htmlFor={name}>{title}</label>
{showError && <div>{errorMessage}</div>}
</div>
)
} Hope this can help :) |
Beta Was this translation helpful? Give feedback.
Hi @MattHeslington
Thanks for the kind word.
You can pass a
defaultValue
tofalse
if nodefaultValue
is provided