Jerin
Jerin

Reputation: 737

How can i get the values of multi dynamic check boxes and store into a reactjs state

From the below UI I want to output something like this on my state. I want if checkmark on ketchup it will store in a array of object or object and after that if I checkmark on extra tomato it will store into the same object.

[{title: 'Barnes Chapman', options:{extra large: '8.0', ketchup: '1.00', extra tomato: '2' } }]

enter image description here

I have created a function but the function is not working properly. Below code is the initial code of my function. inside the product parameter there is title. e means the targeted value and name.

const [item, setItem]= useState()
const getItemValues =(e, product)=>{

}

JSX code: the checkbox values are dynamic. I have commented the values.

 {product.ingredients.map((ingredient) => {
                    return (
                      <li onChange={(e) => getItemValues(e.target, product)}>
                        <label className="container_check">
                          {ingredient.title}  // "ketchup"
                          <span>+ $2</span>
                          <input
                            type="checkbox"
                            value={ingredient.price} // "1"
                            name={ingredient.title} // "ketchup"
                          />
                          <span className="checkmark"></span>
                        </label>
                      </li>
                    );
                  })}

Upvotes: 0

Views: 34

Answers (1)

Gabriel Oliveira
Gabriel Oliveira

Reputation: 11

You might not want the state to be an array. But simply an object.

You can try doing something like:

const options = { ketchup: '1.00' }
setState(oldState => {...oldState, options: {...oldState.options, ...options } })

Upvotes: 1

Related Questions