I am having 3 materialUI TextFields which I want to render n number of times (that n will be a integer input from user before rendering the form field, here I stored it in a variable named groupMembersCount). I am using functional component in ReactJS defining an array with useState hooks as:
const [groupDetails, setGroupDetails] = React.useState([
{ fullName: "", phoneNo: "", gender: "" },
]);
This will be my main array to hold all the 3 values(user input) at their respective indexes. I tried returning those 3 materialUI TextField dynamically by this method:
{Array.apply(null, { length: groupMembersCount }).map(
(e, i) => (
<div key={i}>
<strong>Member #{i + 1}</strong>
<div className="getIndex" name={i + 1}>
<TextField
id={Math.random()}
name="Name"
variant="outlined"
margin="none"
label="Name"
onChange={handleGroupName}
/>
<TextField
id={Math.random()}
name="phoneNo"
variant="outlined"
margin="none"
label="Mobile Number"
onChange={handleGroupPhoneNo}
/>
<TextField
id={Math.random()}
name="gender"
variant="outlined"
margin="none"
label="Gender"
onChange={handleGroupGender}
select
>
<option value="MALE">Male</option>
<option value="FEMALE">Female</option>
<option value="OTHER">Other</option>
</TextField>
</div>
</div>
)
)}
Now in the name handler handleGroupName I am doing this to get the div(to get index [from its name attribute] which stores index to push this value in main array groupDetails):
const handleGroupName = (event) => {
let elem = document.getElementsByClassName("getIndex"); // get div
for (var i = 0; i < groupMembersCount; i++) {
console.log("index is: ", elem[i].getAttribute('name')); // get the index number
}
};
After doing all this I am having issues in few things: 1. One of the form fields (TextField) with gender in name attribute, I'm unable to use select to create a dropdown (writing what is shown here causes a blank screen) so I commented it out. 2. In handleGroupName handler within the for loop it shows the error as: UserDetails.jsx:434 Uncaught TypeError: Cannot read property 'getAttribute' of undefined. 3. I'm new to react functional component, not much experience in it, can anyone suggest some better ways to get values from those form fields for every render and club those as an object and store at different index in the main array, the structure of main array groupDetails defines how it should look like at the end.