How change the format of checkbox in react final form

Viewed 1076

I implemented the form through react final form

const products=  [
    { label: "T Shirt", value: "tshirt" },
    { label: "White Mug", value: "cup" },
    { label: "G-Shock", value: "watch" },
    { label: "Hawaiian Shorts", value: "shorts" },
  ];
<>
<Form
  onSubmit={onSubmit}
  render={({ handleSubmit, pristine, invalid, values }) => (
    <form onSubmit={handleSubmit} className="p-5">
      {products &&
        products.map((product, idx) => (
          <div className="custom-control custom-checkbox" key={idx}>
            <Field
              name="state"
              component="input"
              type="checkbox"
              value={product.value}
            />
            <label
              className="custom-control-label"
              htmlFor={`customCheck1-${product.value}`}
            >
              {product.label}
            </label>
          </div>
        ))}
      <button type="submit" disabled={pristine || invalid}>
        Submit
      </button>
      <pre>{JSON.stringify(values, 0, 2)}</pre>
    </form>
  )}
/>
</>

If I am selecting checkboxes the checked values are showing array of values like [tshirt,cup] but I need to show the array of objects like [ { label: "T Shirt", value: "tshirt" }, { label: "White Mug", value: "cup" }] I tried so many ways but I have not any luck. Please help me to out of this problem

2 Answers

values will always be the array consisting of the "value" attribute for the Field tag. If you want the object from the products array,you could do the following

console.log(values.map(val => products.find(p => p.value === val)))

or create an object first via reduce & then use it.

const obj =products.reduce((map,p)=>{
map[value]=p
return map
},{})

console.log(values.map(v => productMap[v]))

add a onchange method to you input. the method must take value of product.

const [selectedProducts, setSelectedProducts] = useState([]);
    const handleChange = (value) =>{
        const itemToAdd = products.find(product => product.value === value);
        const index = selectedProducts.findIndex(item => item.value === value);

        if (index === -1){
            setSelectedProducts([...selectedProducts, products[index]])
        }else {
            const data = [...selectedProducts];
            data.splice(index, 1);
            setSelectedProducts(data);
        }
    }

some change to jsx

<Field
   onChange = {handleChange}
   name="state"
   component="input"
   type="checkbox"
   value={product.value}
   checked = {selectedProducts.findIndex(item => item.value === value)!== -1}
/>
Related