Home > database >  How to create react form with dynamic fields fetched from api
How to create react form with dynamic fields fetched from api

Time:02-05

I want to create a react form with dynamic inputs, those inputs are fetched from server.

I fetched the data and I have displayed the form but the problem was how to get the values of the inputs with the onChange method

CodePudding user response:

Use a Usestate hook and assign the value fetched from the API there

eg:-

const [value,setValue] = useState(fetch());

function fetch(){

//API call...
//return the value got from the API
}

Now in form input field you can use this as value and have an onChange and change the value state.

eg:-

<input value={value.name} name="name" onChange={(e)=>handlechange(e)} />

in handlechange :

const handlechange = (e)=>{
const {name,value} = e.target;
setValue({...value,[name]:value});
};

After this you can have an useEffect, which will POST the value to the backend using another API for every changes made in the form

Here is the code sandbox link:https://codesandbox.io/s/blazing-moon-wxp4w7?file=/src/App.js

CodePudding user response:

after some researches on stackoverflow here is my solution:

const [fields, setFields] = useState([{field:"", value:""}]);

useEffect(()=>{
 if(fetchedData){
  setFields(fetchedData.map((item)=>{
    var rObj ={field:"", value:""};
    rObj["field"] = item;
    return rObj;
  }));
 }
},[fetchedData])

const handleChange = ( index, event ) => {
 if(fields) {
  let data = [...fields];
  data[index]["value"] = event.target.value;
  setFields(data);
 }
}

/////////////////////////////////////////
{fetchedData.map((field, index) => (
   <div key={index}>
     <input 
       required
       type="text" 
       name={field}
       value={fields.field}
       placeholder= {field}
       onChange={event=>{handleChange(index, event)}}
      />
    </div>
   ))}
  • Related