Reputation: 635
I developed a component for checkbox using React Formik Library.Below is my code
const CheckBoxGroup = (props) => {
const { label,name,options,...rest } = props
return (
<React.Fragment>
<label htmlFor={name}> {label} </label>
<div className='form-check form-check-inline'>
<Field name={name} id={name} {...rest} >
{
({field}) => {
return options.map( (option) => {
return ( <React.Fragment key={option.key}>
<input type="checkbox"
id={option.value} {...field} value={option.value}
checked={field.value.includes(option.value)}
/>
<label class="form-check-label" htmlFor={option.value}>{option.key}</label>
</React.Fragment>)
})
}
}
</Field>
<ErrorMessage name={name} component={TextError} />
</div>
</React.Fragment>
);
}
Interesting part is that when checked property is present the checkbox is not cheked but if i remove checked property it is checked.what is the reason?
Upvotes: 4
Views: 4151
Reputation: 391
In my case use value atribute as number but works only with string
<Field
className="form-check-input"
type="checkbox"
name="idsProfiles"
id={item.defaultText}
value={item.id.toString()}
aria-label={item.defaultText}
/>
<label htmlFor={item.defaultText}>
{item.defaultText}
</label>
Upvotes: 4
Reputation: 130
you can check the docs on the formik web page, here is a local implementation to try the demo checkbox and it's running ok, i used the last formik lib version.
here is the example from formik site: formik checkboxex codesandbox demo
***i cannot replicate you code because you miss the inputs on the props
here is what i run on local:
import React from 'react';
import { Field, Formik ,Form } from 'formik';
import './App.css';
function App() {
///FORMIK DOCS:
///https://formik.org/docs/examples/checkboxes
const CheckBoxGroup = (props) => {
const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
return (
<Formik
initialValues={{
toggle: false,
checked: [],
}}
onSubmit={async (values) => {
await sleep(500);
alert(JSON.stringify(values, null, 2));
}}
>
{({ values }) => (
<Form>
<label>
<Field type="checkbox" name="toggle" />
{`${values.toggle}`}
</label>
<div id="checkbox-group">Checked</div>
<div role="group" aria-labelledby="checkbox-group">
<label>
<Field type="checkbox" name="checked" value="One" />
One
</label>
<label>
<Field type="checkbox" name="checked" value="Two" />
Two
</label>
<label>
<Field type="checkbox" name="checked" value="Three" />
Three
</label>
</div>
<button type="submit">Submit</button>
</Form>
)}
</Formik>
);
}
return (
<div className="App">
{CheckBoxGroup()}
</div>
);
}
export default App;
Upvotes: 0