Reputation: 820
I am using react-hook-form for the validation of my form in react.
What I am doing
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.
Upvotes: 2
Views: 2340
Reputation: 81370
When using form
, any input elements (input
, select
...) inside it is identified via a name
attribute, not id
as you may think.
map(_, index) => (
<input
name={`name[${index}]`}
ref={register}
/>
)
When you log the submit data, here is what it looks like
{
"name": ["1", "2", "3"]
}
Error displaying:
{errors.name && errors.name[index] && (
<div>
{errors.name[index].message}
</div>
)}
map(_, index) => (
<input
name={`data[${index}].name`}
ref={register}
/>
)
Output
{
"data": [
{ "name": "1" },
{ "name": "2" },
{ "name": "3" }
]
}
Error displaying
{errors.data && errors.data[index] && errors.data[index].name && (
<div>
{errors.data[index].name.message}
</div>
)}
map(_, index) => (
<input
name={`name_${index}`}
ref={register}
/>
)
Output:
{
"name_0": "1",
"name_1": "2",
"name_2": "3"
}
Error displaying:
{errors["name_" + index] && (
<div>
{errors["name_" + index].message}
</div>
)}
Upvotes: 2
Reputation: 2317
I think you shoud simply change the input name
li ke this
...
<input
type="text"
name={'name' + index} // you should change this
id={'name' + index}
className="form-control"
placeholder="F Name"
ref={register({required: 'F name is required'})}
/>
...
Upvotes: 0