I'm new to Formik and need to create dynamic form which can contain multiple entries of the same type. I use a list of objects to keep track of newly added entries as follows.
-- At the rendering element level
const [vehicles, setVehicles] = useState([{make: "", model: "", year: ""}]);
In the render function, within the form I use map to render multiple input elements, bind with above objects. I can't use Formik initialValues since there will be new entries added by the user upon a button click.
{vehicles.map((vehicle, i) => {
return (
<div key={i}>
<TextField
fullWidth
label="Make"
name="make"
onBlur={handleBlur}
onChange={handleChange}
value={vehicle.make}
variant="outlined"
/>
<!-- other input boxes as well -->
</div>
);
})};
The problem here is, I can't update value of text box since vehicle.maker isn't updating when I type in the text box.
If you are going to use array of objects, I suggest you to implement it this way. You can still use initialValues even if there are going to be new entries.
First, generate your validation schema
Write your initial values
Import
Implement
NOTE: If you want to remove an item, you can use
arrayHelpers.remove(index)(index from values.vehicles.map function)