lundi 18 avril 2022

react formik how pass value and id from checkbox component

Here is my checkbox component:

function CheckBoxesControl(props) {
  const { label, name, options, ...rest } = props;

  return (
    <div className='checkbox-control'>
      <span className='checkbox-title'>{label}</span>
      <div className='check-elements'>
        <Field name={name}>
          {({ field, form }) => {
            return options.map((option) => {
              return (
                <React.Fragment key={option.key}>
                  <input
                    type='checkbox'
                    id={option.key}
                    {...field}
                    {...rest}
                    value={option.value}
                    checked={field.value.includes(option.value)}
                  />
                  <label htmlFor={option.value}>{option.value}</label>
                </React.Fragment>
              );
            });
          }}
        </Field>
      </div>
      <ErrorMessage component={TextError} name={name} />
    </div>
  );
}
export default CheckBoxesControl;

Code for FormikControl:

import React from 'react';
import CheckBoxesControl from './checkboxescontrol';
import RadioButtons from './radiobuttons';

function FormikControl(props) {
  const { control, ...rest } = props;

  switch (control) {
    case 'radio':
      return <RadioButtons {...rest} />;
    case 'checkbox':
      return <CheckBoxesControl {...rest} />;

    default:
      return null;
  }
}

export default FormikControl;

And parent component:

 <Formik
            initialValues={formValues || initialValues}
            validationSchema={validationSchema}
            validateOnMount
            onSubmit={onSubmit}
            enableReinitialize 
      >
        {(formikProps) => {
            return (
                <Form>
                <FormikControl
                    control='checkbox'
                    label='Categorie carte'
                    name='categorieCarte'
                    options={filtreazaCategorieCarte}
                  />
    
                </Form>
     </Formik>

filtreazaCategorieCarte - it is an array that I get from firestore that looks like this: [{key:'', value:''}]

I am a beginner, so please bear with me:
Currently all I can get is either option.value or option.key
What I want is the value from checked checkbox send to formik to look like this:
[id: option.id, name: option.value]

Is it possible ?




Aucun commentaire:

Enregistrer un commentaire