Home > OS >  Getting and Inserting array of objects from checkboxes ReactJS
Getting and Inserting array of objects from checkboxes ReactJS

Time:11-19

I am having a trouble where an array of Objects are returning [Object object]. What could be the missing fix to get the value of product from the mapped targeted values.

this is my sample array.

const product = [{food:'BREAD',price: 6}]

this is where I map the values and get the targeted value.

<Form >
                    {product.map((item, index) => (
                      <div key={index} className="mb-3">
                        <Form.Check
                          input value={[item]}
                          id={[item.food]}
                          type="checkbox"
                          label={`${item.food}`}
                          onClick={handleChangeCheckbox('PRODUCTS')}
                          
                        />
                      </div>
                    ))}
                  </Form>

this handles the e.target.value from checked checkboxes.

  const handleChangeCheckbox = input => event => {
    var value = event.target.value;
    var isChecked = event.target.checked;
    setChecked(current =>
      current.map(obj => {
        if (obj.option === input) {
          if(isChecked){
          return {...obj, chosen:  [...obj.chosen, value ] };
          }else{
            var newArr = obj.chosen;
            var index = newArr.indexOf(event.target.value);
            newArr.splice(index, 1); // 2nd parameter means remove one item only
            return {...obj, chosen: newArr};
          }
        }
        return obj;
      }),
    );
    console.log(checked);
  }

finally, this is where I am having problems. Chosen is returning [Object object]console.log(checked).

 const [checked, setChecked] = useState([
    { option: 'PRODUCTS',
      chosen: [],
    }
]);

What do I insert inside chosen:[] to read the following arrays. Im expecting to see

0: 
 food: 'bread'
 price: '6'

Thank you so much for helping me!

CodePudding user response:

Html input value prop is a string, and it's change event target value is also string.

Here you are passing an object to the value prop, which will be stringified as [Object object].

Instead, update your change handler to take item instead of event.

const handleChangeCheckbox = (input) => (value) => {
  setChecked((current) => {
    // Value is checked if it exists in the current chosen array
    const isChecked = current.chosen.find((item) => item.food === value.food) !== undefined;

    // Remove it from state
    if (isChecked) {
      return {
        ...current,
        chosen: current.chosen.filter((item) => item.food === value.food),
      };
    }

    // Add it to state
    return {
      ...current,
      chosen: [...current, value],
    };
  });
};

Then update your input element onChange handler, to call your handler with the item itself, instead of the event.

onClick={() => handleChangeCheckbox('PRODUCTS', item)}

I don't know what the props for your component Form.Check are. But, I would expect an input type="checkbox" to have a checked prop.

A checkbox is checked if the item is in the chosen state array.

<Form>
  {product.map((item, index) => (
    <div key={item.food} className="mb-3">
      <Form.Check
        type="checkbox"
        id={item.food}
        label={item.food}
        checked={checked.chosen.find((chosen) => chosen.food === item.food) !== undefined}
        onClick={() => handleChangeCheckbox('PRODUCTS', item)}
      />
    </div>
  ))}
</Form>

CodePudding user response:

Hmm, don't you need to inline your handleChangeCheckbox function? As otherwise it's just getting executed. So instead onClick={handleChangeCheckbox('PRODUCTS')} do onClick={(event) => handleChangeCheckbox('PRODUCTS', event)}.

Then your handleChangeCheckbox function will start handleChangeCheckbox = (input, event) => {...}

  • Related