I am working with react and making some new input fields dynamically, and using React-gook-form for validation.
What I am doing is -
- I have one dropdown in which I have numbers as dropdown, like 1,2,3,4
- So which ever dropdown user is selecting I am creating that much input field
- if user selects 3 then 3 input fields
What I am trying to achieve is
- When user create two input fields i do not want both of them to have same input.
- Like if first input is having D as input then the second one should not take
Din second one.
PS- here just for minimal code i am creating only one set of input, like first name
It can be when i select 2 then I can create two set of inputs having Fname and Lname in each set so there both fname should not take same value and same goes for lname.
What I have done
this one to hold the state, initial one is selected and one input is created.
const [initialSet, setinitialSet] = useState(1);
On select change doing this
const Select_change = (e) => {
let val = parseInt(e.target.value);
setinitialSet(val);
};
Now using that initial state to loop my elements to create input fields
<div className="row">
{[...Array(initialSet).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={`data[${index}].name`}
id={"name" + index}
className="form-control"
placeholder="F Name"
ref={register({ required: `F name ${index} is required` })}
/>
<label" htmlFor={"name" + index}>
F Name
</label>
{errors.data && errors.data[index] && errors.data[index].name && (
<div>
<span className="text-danger">
{errors.data[index].name.message}
</span>
</div>
)}
</div>
</div>
))}
</div>
Now I just want to validate the fname so that two input fields of f name should not have same input.
I have full working code in my code sandbox