Home > Enterprise >  Dynamic Input field in React Formik
Dynamic Input field in React Formik

Time:12-07

I have form where it has an input and a date picker, these two will be coming from an API endpoint.

How do I save the input values ?

const [startDate, setStartDate] = useState(new Date());

const apiData = [
    {id: "abc", name: "form 1"},
    {id: "abd", name: "form 2"},
    {id: "abz", name: "form 3"},
    {id: "asd", name: "form 4"},
    {id: "acd", name: "form 5"},
];
...   
{apiData?.map((item) => {
    return (
       <input // accept only number
           type="text"
           name={item.id}
           placeholder="Fee"
           className="fee-form"
       />
       <DatePicker
           selected={startDate}
           onChange={(date) => setStartDate(date)}
           className="date-pic-brand-form"
       />
    );
})}

This above code will generate the 5 form fields.

How to save the data for each of the input fields ?

Thank you.

CodePudding user response:

Something like this:

const [data, setData] = useState([]);

const apiData = [
    {id: "abc", name: "form 1"},
    {id: "abd", name: "form 2"},
    {id: "abz", name: "form 3"},
    {id: "asd", name: "form 4"},
    {id: "acd", name: "form 5"},
];
...   

useEffect(() => {
    const newData = [];
    apiData.forEach(() => {
        newData.push({});
    });
    setData(newData);
}, [apiData]);

const handleChange = (field, value, index) => {
    setData(prevState => {
        const nextState = [...prevState];
        nextState[index][field] = value;
        return nextState;
    })
}
{
    apiData?.map((item, index) => {
    return (
    <input // accept only number
        type="text"
        name={item.id}
        placeholder="Fee"
        className="fee-form"
        onChange={e => handleChange('id', e.target.value, index)}
    />
    <DatePicker
        selected={startDate}
        onChange={date => handleChange('date', date, index)}
        className="date-pic-brand-form"
    />
    );
})}

And in the end you have all data inside data state.

  • Related