Umarkhon
Umarkhon

Reputation: 171

How to create dynamic objects inside dynamic objects

This is created another objects dynamically when you click a button. But I want to create new object inside questions Array when I click a button.

const [inputFields, setInputFields] = useState([
    {
      sectionName: "",
      sectionDesc: "",
      questions: [{ questionType: "", questionText: "" }],
    },
  ]);
const handleChange = (index: any, event: any) => {
    const values = [...inputFields];
    // @ts-ignore
    values[index][event.target.name] = event.target.value;
    setInputFields(values);
    console.log(index, event.target.name);
  };

const handleAddFields = () => {
    setInputFields([
      ...inputFields,
      {
        sectionName: "",
        sectionDesc: "",
        questions: [{ questionType: "", questionText: "" }],
      },
    ]);
  };

Upvotes: 0

Views: 92

Answers (1)

pilchard
pilchard

Reputation: 12911

First off, you are mutating state in your handleChange handler. You can avoid this using map()

const handleChange = (index: number, event: React.ChangeEvent<HTMLInputElement>) => {
  setInputFields(prev => prev.map((p, i) => (
    i === index
      ? {
        ...p,
        [event.target.name]: event.target.value
      }
      : p
  )));
};

As for adding to the questions array, you will need an index for which object you want to add to, then use the same technique as above to spread into that object.

const handleAddFields = (index: number) => {
  setInputFields(prev => prev.map((p, i) => (
    i === index
      ? {
        ...p,
        questions: [...p.questions, { questionType: "", questionText: "" }]
      }
      : p)
  ));
};

Note: Using any for all parameters defeats the purpose of typing, try to use relevant types to take advantage of the type system.

Upvotes: 1

Related Questions