0

Suppose we have this form right here full of key values pairs (i.e. in this case)

const data = {
  maxPosts: 9999999,
  key: "value"
};

However there can be more key-value pairs and hence more inputs in the picture below.

What is a good way of handling the input change depending on the data given? Because I cannot hardcode all the input handlers like such (as the inputs are dependent on the KV Pairs):


      changeKey1: function (event) {
        // change state
      },
      changeVal1: function (event) {
        // Change State
      },
      changeKey2: function (event) {
        // Change State
      },

Ultimately the user will be editing these values and then press submit to confirm their edit changes. Is there anyway of doing this with React Hooks?

enter image description here

bigfocalchord
  • 553
  • 1
  • 7
  • 14
  • Possible duplicate of [generic event handler to set the state of any form field](https://stackoverflow.com/questions/43065940/generic-event-handler-to-set-the-state-of-any-form-field) and [React.js: Identifying different inputs with one onChange handler](https://stackoverflow.com/questions/21029999) – adiga Jul 16 '19 at 19:40
  • @adiga I was wondering if the same behaviour could be replicated with React Hooks – bigfocalchord Jul 16 '19 at 19:42

1 Answers1

0

Yes, here is a simple example of managing N states.

const generateNValues = N => [...Array(N).keys()];

function TextAreaManager() {
  const [valuesManager, setValuesManager] = useState(generateNValues(10));
  return (
    <Flexbox>
      {valuesManager.map((value, i) => (
        <TextBoxItem
          key={i}
          value={value}
          onChange={e => {
            valuesManager[i] = e.target.value;
            setValuesManager([...valuesManager]);
          }}
        />
      ))}
      <PinkButton
        onClick={() =>
          setValuesManager([...Array(valuesManager.length).fill('')])
        }
      >
        Reset All
      </PinkButton>
    </Flexbox>
  );
}

Edit OS Q 556724228 - Manage dynamic form state

Dennis Vash
  • 50,196
  • 9
  • 100
  • 118