I got the following error "TypeError: undefined is not a function (near '...formFields.map...')" when trying to render the below react script. Does anyone have any idea why I am getting this error?
import React, { useState, Fragment } from "react";
import { Container } from "@material-ui/core";
export default function DynamicFields() {
const [formFields, setFormFields] = useState({
id: 0,
firstName: "",
lastName: "",
});
const [nextFieldIndex, setNextFieldIndex] = useState(1);
const handleSubmit = (e) => {
e.preventDefault();
console.log("Input fields: ", formFields);
};
const handleChange = (id, e) => {
let newFields = formFields.map((fieldSet) => {
if (fieldSet.id === id) {
fieldSet[e.target.name] = e.target.value;
}
return fieldSet;
});
setFormFields(newFields);
};
return (
<Container>
<h3>Add a name</h3>
<form onSubmit={handleSubmit}>
{formFields.map((fieldSet) => (
<div key={fieldSet.id}>
<input
type="text"
name="firstName"
value={fieldSet.firstName}
onChange={(e) => handleChange(fieldSet.id, e)}
/>
<input
type="text"
name="lastName"
value={fieldSet.firstName}
onChange={(e) => handleChange(fieldSet.id, e)}
/>
</div>
))}
</form>
</Container>
);
}
I am unsure why this is happening and I was roughly following a tutorial but this still happened. Any advise would be much appreciated.
formFields
isn't an array, should modify your formFields
state to this:
const [formFields, setFormFields] = useState([
{
id: 0,
firstName: "",
lastName: "",
}
])
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.