I am working on creating dynamic elements, when User clicks on add
I am creating another set of elements.
once I am creating the elements I have one select option there so on selection of particular options I am creating one more field.
I have first name
and select age
two elements, there I have age as >18
and <=18
so on this basis I am creating one more field.
Here when I am creating one more field I am facing issue.
What I am doing
I am looping my elements
then for new element which I going to be created on selection I am doing conditional rendering
{onChangeAge && indexVal === index && (
So What I am doing is when onChange of select I am checking the value if it is >18 then setting state to that value and showing the new input field,
>18
in first set of element and selecting <=18
in second then it is again setting as false.indexVal === index
I don't know how to handle thatIssue
The issue is when I am selecting age <=18
the I am showing one input field, the I created one more element set
and there if I am again selecting <=18
then the Input field I have created in first component is not showing up.
This is my code sandbox link In my code sand box I have working code, please do check
I would suggest either keep track of age input by updating existing inputHolder
or track via separate state. It would be like this:
Update onChange age
const onChangeAge = (e, ind) => {
console.log(e.target.value);
let val = e.target.value;
console.log(typeof ind, ind, typeof val);
let inputHolderCopy = [...inputHolder];
setindexVal(ind);
inputHolderCopy = inputHolderCopy.map((data) => {
if (data.id === ind + 1) {
return { ...data, currentSelectedAge: val };
}
return data;
});
setinputHolder(inputHolderCopy);
if (val === "<=18 ") {
console.log("Hello");
setageVal(true);
} else {
setageVal(false);
}
}
Now simply check here:
{onChangeAge && li.currentSelectedAge === "<=18" && (
<div>
<input
type="text"
name={`data[${index}].idCred`}
id="idCred"
placeholder="ID"
ref={register({ required: "ID is required" })}
/>
<br></br>
<label htmlFor="idCred">Name</label>
</div>
)}
here is the demo: https://codesandbox.io/s/proud-river-5bg7o?file=/src/App.js:2093-2527
Note: This is just one approach. You can do other way also. Like creating variable in inputHolder
and keep track its value.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.