I am using react-hook-form for the validation of my form in react.
What I am doing
- I have one select dropdown, which has some numbers as a dropdown.
- On change of select dropdown I am creating the input field, if 2 is selected then 2 input field, initially one is there by default.
- Now when I select 2 or 3 options and create 2-3 input fields, on click of a button it is only taking last field validation as well as giving me the last field value only.
In react-hook-form
we use ref
to hold the value of particular input and for validation as well.
But here it is only validating the last one only, I do not know what I am missing.
This is what I am doing.
<div className="row">
{[...Array(inputHolder).keys()].map((li, index) => (
<div className="col-12 col-sm-12 col-md-8 col-lg-4 col-xl-4">
<div className="form-group">
<input
type="text"
name="name"
id={'name' + index}
className="form-control"
placeholder="F Name"
ref={register({required: 'F name is required'})}
/>
<label className="common_label_form" htmlFor={'name' + index}>
F Name
</label>
{errors.name && (
<div>
<span className="text-danger">{errors.name.message}</span>
</div>
)}
</div>
</div>
))}
</div>;
I need to make my refs
dynamic but I don't know how can I achieve that.
I want to have data like [{ name: 'name1' }, { name: 'name2' }]
, that's why I have been stuck, once I will get data then I can push it inside array.
When using
form
, any input elements (input
,select
...) inside it is identified via aname
attribute, notid
as you may think.Solution 1:
When you log the submit data, here is what it looks like
Error displaying:
Solution 2:
Output
Error displaying
Solution 3:
Output:
Error displaying:
Live Demo