skip to Main Content

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

2

Answers


  1. I think the problem is not with the map function but with the values of the object you are passing. If you want to create a dynamic field you can follow this post https://nainacodes.com/blog/create-form-from-json-schema
    or you can define an onChange function and pass it directly in the input without defining it in the fields object.

    Login or Signup to reply.
  2. 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}
    />
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search