hellomello
hellomello

Reputation: 8587

ReactJS Complex Form Input Field Duplicating Text in Multiple Input Fields

I have a form where you can add/remove groups and input items, I was able to get the groups of input field working, but I'm having trouble with the items input within the respected groups:

I created a code sand box here: https://codesandbox.io/s/twilight-cache-4ipv6?file=/src/Form.jsx

If you click on Add Items + button, and type in the item fields, the value duplicates to all the fields.

Also, sometimes I feel like the x button doesn't work, and will only remove the last item or something, I believe this is "controlled component?"

In addition, I want to ask if there's a better method on what I'm doing? It seems like there's a lot of complexities in the code I'm trying to write up. I feel like I'm writing too much of the set state hooks.

Upvotes: 0

Views: 1017

Answers (1)

Ryuko
Ryuko

Reputation: 377

I think we don't need that fields state.

And we can update Add Handlers like this


  const handleAddGroup = i => {
    const newGroup = [...group];
    newGroup.push({
      id: null,
      cat: "",
      items: [
        {
          name: "",
          value: ""
        }
      ]
    });

    setGroups(newGroup);
  };

  const handleAddField = i => {
    setGroups(state => {
      const stateCopy = JSON.parse(JSON.stringify(state));

      stateCopy[i].items.push({
        name: "",
        value: ""
      });

      return stateCopy;
    });
  };

https://codesandbox.io/s/cool-frog-2yrlt

Upvotes: 1

Related Questions