Use map() with useState and functions

I am new to React and I have a question.

I have two useStates

const [min, setMin] = useState("");
const [new, setNew] = useState("");

A function that takes the value of the first parameter and, after a check, uses the second parameter to make the set of the useState

const checkOne = (evt, setstate) => {
    const result = ......;
    setstate(result);
}

And an object.
This has a "value" field with the value of the useState.
A "check" field that calls a check function that then values the useState.

const fields =  [{"id":1, "value": {min}, "check": {checkOne(e, setMin)}, "label": 'text1, "placehoder": "15"},
                 {"id":2, "value": {new}, "check": {checkTwo(e, setNew)}, "label": 'text2, "placehoder": "10"},
                ];
            

When I use map(), how can I enhance the value field (with "value") and the onChange event (with the "check" field)?

{fields.map((dev) =>
    <div key={dev.id}>
        <label>{dev.label}</label><br/>
        <input type="text" value={XXX} onChange={YYY} placeholder={dev.placehoder} />
    </div>
)}

Thanks for the help

>Solution :

You need to make the check field a reference and not call the function.

Here’s how:

  const [min, setMin] = useState('');
  const [val, setVal] = useState('');

  const checkOne = (evt, setState) => {
    const result = evt.target.value;
    setState(result);
  };

  const fields = [
    {
      id: 1,
      value: min,
      check: (e) => checkOne(e, setMin),
      label: 'text1, "placehoder": "15"',
    },
    {
      id: 2,
      value: val,
      check: (e) => checkOne(e, setVal),
      label: 'text2, "placehoder": "10"',
    },
  ];

And then render it like:

<input
  type='text'
  value={dev.value}
  onChange={(e)=>dev.check(e)}
  placeholder={dev.placehoder}
/>

Leave a Reply