Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Checkbox is not checked in React Formik

Tags:

reactjs

formik

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?

like image 569
user3692033 Avatar asked Oct 28 '25 14:10

user3692033


1 Answers

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>
like image 93
Yurifull Avatar answered Oct 30 '25 05:10

Yurifull