In React, I am using onSubmit
to call function and then updating multiple states in the function. I have repeated Director Name fields in the form where user can click on + icon and add a new field. The fields are named as "DirectorName1"
, "DirectorName2"
and so on.
I am also saving total number of Directors in a different state value.
In function, I am looping through total number of Directors and then trying to access DirectorName
field's value and concatenating the array index number in value.
Here is the code:
let newIndex = '';
{[...Array(aboutDetails.companyDirectors)].map((elementInArray, index) => (
newIndex = index + 1,
console.log(event.target.directorName + index.value)
))}
But it shows the value as NaN
. The main issue I am getting is I am unable to append index number dynamically in event.target.directorName
.
If the logic is an a form
element's onSubmit
handler and directorName
is one of the form fields then you should be accessing directorName.value
to get the field value.
The array index
is also a number type, so index.value
is
undefined. You likely just want to reference index
, or rather, the computed newIndex
value.
The Array.prototype.map
callback function is returning a Comma Operator expression, so the result of the console.log
, i.e. undefined
is returned as the mapped array element value.
The array is being mapped to new values, but the returned mapped array isn't saved or referenced.
const directorNames = aboutDetails.companyDirectors
.map((elementInArray, index) => {
const newIndex = index + 1;
const newDirectorName = event.target.directorName.value + String(newIndex);
console.log({ newDirectorName });
return newDirectorName; // <-- return mapped value!
});