skip to Main Content

I have these components and I have 12 checkboxes in child component. I want to have them checked by default when the component loads. I can’t do that. I can’t use checked='true' as an attribute for my input because formik is controlling my input and it doesn’t work well. Or I set checked attribute with some pre-defined values in checked array, but again it worked badly. I thought I probably can use useRef here to trigger onChange event of input to simulate changing checkboxes by checking them. something like this:

const ref = useRef();

useEffect(() => {
ref.current.change();
}, [])

and setting ref to the input. But this didn’t work. How can I fix this problem with ref or something else?

    import {useFormik} from "formik";
    import CheckboxesComponent from "./CheckboxesComponent";
    
    const AddUserForm = ({handleShowForm, showForm, formTitle}) => {
        const cities = options.slice(1)
        const [textAreaString, setTextArea] = useState('')
    
        const formik = useFormik({
            initialValues: {
                tel: '', name: '', password: '', username: '', province: '', level: '', availableCities: '', city: '',
                checked: []
            },
            onSubmit: values => {
                console.log(formik.values)
            }
        })
    
        return(
            <form className='add-user-form' onSubmit={formik.handleSubmit}>
                <div className='form-flex'>
                   {/*other parts of form*/}
                </div>
                <CheckboxesComponent handleChange={formik.handleChange} />
            </form>
        )
    }
    export default AddUserForm

CheckBoxesComponent:

const fields = [
    {name: 'delNomad', label: 'حذف عشایر'},
    {name: 'editNomad', label: 'ویرایش عشایر'},
    {name: 'addNomad', label: 'افزودن عشایر'},
    {name: 'delDriver', label: 'حذف راننده'},
    {name: 'editDriver', label: 'ویرایش راننده'},
    {name: 'addDriver', label: 'افزودن راننده'},
    {name: 'rejectReq', label: 'رد درخواست ها'},
    {name: 'manualDeliver', label: 'تایید تحویل دستی'},
    {name: 'addWaterReq', label: 'افزودن درخواست آب'},
    {name: 'getExcel', label: 'دریافت فایل اکسل'},
    {name: 'seeingReport', label: 'مشاهده گزارش گیری'},
    {name: 'delReq', label: 'حذف درخواست ها'},
];

const CheckboxesComponent = ({handleChange}) => {

    return(
        <div className='checkboxes-part'>
            {fields.map((item, index) => {
                return(
                    <div>
                        <label>{item.label}</label>
                        <input type='checkbox' name='checked' value={item.name} onChange={handleChange} />
                    </div>
                )
            })}
        </div>
    )
}

export default CheckboxesComponent

2

Answers


  1. Chosen as BEST ANSWER

    It was fixed by setting a defaultChecked to checkboxes:

    import {useFormik} from "formik";
    import CheckboxesComponent from "./CheckboxesComponent";
    
    const AddUserForm = ({handleShowForm, showForm, formTitle}) => {
        const cities = options.slice(1)
        const [textAreaString, setTextArea] = useState('')
    
        const formik = useFormik({
            initialValues: {
                tel: '', name: '', password: '', username: '', province: '', level: '', availableCities: '', city: '',
                checked: ['delNomad','editNomad','addNomad','delDriver','editDriver','addDriver','rejectReq','manualDeliver',
                'addWaterReq','getExcel','seeingReport','delReq']
            },
            onSubmit: values => {
                console.log(formik.values)
            }
        })
    
        return(
            <form className='add-user-form' onSubmit={formik.handleSubmit}>
                <div className='form-flex'>
                   {/*other parts of form*/}
                </div>
                <CheckboxesComponent handleChange={formik.handleChange} />
            </form>
        )
    }
    export default AddUserForm
    
    
    const fields = [
        {name: 'delNomad', label: 'حذف عشایر'},
        {name: 'editNomad', label: 'ویرایش عشایر'},
        {name: 'addNomad', label: 'افزودن عشایر'},
        {name: 'delDriver', label: 'حذف راننده'},
        {name: 'editDriver', label: 'ویرایش راننده'},
        {name: 'addDriver', label: 'افزودن راننده'},
        {name: 'rejectReq', label: 'رد درخواست ها'},
        {name: 'manualDeliver', label: 'تایید تحویل دستی'},
        {name: 'addWaterReq', label: 'افزودن درخواست آب'},
        {name: 'getExcel', label: 'دریافت فایل اکسل'},
        {name: 'seeingReport', label: 'مشاهده گزارش گیری'},
        {name: 'delReq', label: 'حذف درخواست ها'},
    ];
    
    const CheckboxesComponent = ({handleChange}) => {
    
        return(
            <div className='checkboxes-part'>
                {fields.map((item, index) => {
                    return(
                        <div key={index}>
                            <label>{item.label}</label>
                            <input type='checkbox' defaultChecked={true} name='checked' value={item.name} onChange={handleChange} />
                        </div>
                    )
                })}
            </div>
        )
    }
    
    export default CheckboxesComponent
    

  2. you have to add checked attribute in input and also check with value of formic something like below.

    const fields = [
        { name: 'delNomad', label: 'حذف عشایر' },
        { name: 'editNomad', label: 'ویرایش عشایر' },
        { name: 'addNomad', label: 'افزودن عشایر' },
        { name: 'delDriver', label: 'حذف راننده' },
        { name: 'editDriver', label: 'ویرایش راننده' },
        { name: 'addDriver', label: 'افزودن راننده' },
        { name: 'rejectReq', label: 'رد درخواست ها' },
        { name: 'manualDeliver', label: 'تایید تحویل دستی' },
        { name: 'addWaterReq', label: 'افزودن درخواست آب' },
        { name: 'getExcel', label: 'دریافت فایل اکسل' },
        { name: 'seeingReport', label: 'مشاهده گزارش گیری' },
        { name: 'delReq', label: 'حذف درخواست ها' },
    ];
    
    const CheckboxesComponent = ({ checklist, handleChange }) => {
    
        return (
            <div className='checkboxes-part'>
                {
                    fields.map((item, index) => {
                        return (
                            <div key={index}>
                                <label>{item.label}</label>
                                <input type='checkbox' name='checked' value={item.name} checked={checklist.some((FieldItem) => item.name === FieldItem)} onChange={handleChange} />
                            </div>
                        )
                    })
                }
            </div>
        )
    }
    
    export default CheckboxesComponent;
    

    add user form should be like this

    import {useFormik} from "formik";
    import CheckboxesComponent from "./CheckboxesComponent";
    
    const AddUserForm = ({handleShowForm, showForm, formTitle}) => {
        const cities = options.slice(1)
        const [textAreaString, setTextArea] = useState('')
    
        const formik = useFormik({
            initialValues: {
                tel: '', name: '', password: '', username: '', province: '', level: '', availableCities: '', city: '',
                checked: ['delNomad','editNomad','addNomad','delDriver','editDriver','addDriver','rejectReq','manualDeliver','addWaterReq','getExcel','seeingReport','delReq']
            },
            onSubmit: values => {
                console.log(formik.values)
            }
        })
    
        return(
            <form className='add-user-form' onSubmit={formik.handleSubmit}>
                <div className='form-flex'>
                    {/*other parts of form*/}
                </div>
                <CheckboxesComponent checklist={formik.values.checked} handleChange={formik.handleChange} />
            </form>
        )
    }
    export default AddUserForm;
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search