0

I want to insert a new object inside the options which is an array property inside the select1 object every time the user clicks on add button, how can I achieve this target, pls reply to this query.

I want to build a simple application where a user enters the options in the select box and can apply conditions based upon the selected option.

const [select1, setSelect1] = useState({
    id: uuid(),
    type: 'select',
    properties: {
      label: 'Select1',
      options: [
        {
          id: uuid(),
          label: 'text1',
          value: {
            labelTxt: 'text1',
            childOptions: [],
          },
        },
        {
          id: uuid(),
          label: 'text2',
          value: {
            labelTxt: 'text2',
            childOptions: [],
          },
        },
      ],
    },
    parentId: null,
  });

  function addOptionsVal() {
    setSelect1((prevState) => {
      const options = [...prevState.properties.options];
      options.splice(1, 0, {
        id: uuid(),
        label: optionVal,
        value: {
          labelTxt: optionVal,
          childOptions: [],
        },
      });
      console.log(options);
      return { ...prevState, options };
    });
  }

return (
 <div>
        <select name="" id="">
          <option value="">--select--</option>
          {select1.properties.options.map((option) => {
            return <option>{option.label}</option>;
          })}
        </select>
      </div>
        <input
          type="text"
          value={optionVal}
          onChange={(e) => handleValueChange(e)}
        />
        <button onClick={addOptionsVal}>Add options</button>
      </div>
      <div>
        <input
          type="checkbox"
          value="male"
          checked={checked}
          onChange={toggleCondition}
          id="condition"
        />
        <label htmlFor="condition">Apply condition</label>
      </div>
)

This is the entire code file in case you need

Lin Du
  • 88,126
  • 95
  • 281
  • 483

1 Answers1

0

Try this:

function addOptionsVal() {
  setSelect1((prevState) => {
    return {
      ...prevState,
      properties: {
        ...prevState.properties,
        options: [
          ...prevState.properties.options,
          {
            id: uuid(),
            label: optionVal,
            value: {
              labelTxt: optionVal,
              childOptions: [],
            },
          },
        ],
      },
    };
  });
}

stackblitz

Also, take a look at this question Correct modification of state arrays in React.js

Lin Du
  • 88,126
  • 95
  • 281
  • 483