I have some problems regarding React code. Inside my App.jsx
, I wrote the logic with and without the destructuring of an object I get from an jsx tag:
<input
name="fName"
placeholder="First Name"
onChange={handleChange}
value={fullName.fName}
/>
<input
name="lName"
placeholder="Last Name"
onChange={handleChange}
value={fullName.lName}
/>
Here is the code with destructuring way:
function handleChange(event) {
const { name, value } = event.target;
setFullName((preValue) => {
if (name === "fName") {
return {
fName: value,
lName: preValue.lName,
};
} else if (name === "lName") {
return {
fName: preValue.fName,
lName: value,
};
}
});
}
While this is the code without destructuring way
function handleChange(event) {
setFullName((preValue) => {
if (event.target.name === "fName") {
return {
fName: event.target.value,
lName: preValue.lName,
};
} else if (event.target.name === "lName") {
return {
fName: preValue.fName,
lName: event.target.value,
};
}
});
}
Note that I tried to write the code with the same logic. However, while the former does work, in the latter way, my code doesn’t work and starts to crash showing this error:
TypeError
Cannot read properties of null (reading 'name')
eval
/src/components/App.jsx:11:23
8 |
9 | function handleChange(event) {
10 | setFullName((preValue) => {
> 11 | if (event.target.name === "fName") {
| ^
12 | return {
13 | fName: event.target.value,
14 | lName: preValue.lName,
I expect it to work even when I do not use the destructuring