I have a parent component which is like this:
import "./styles.css";
import ChildComponent from "./childComponent";
import { useState, useEffect } from "react";
const persons = [
{
id: 1,
name: "foo",
age: 20,
},
];
export default function App() {
const [data, setdata] = useState(persons);
const updateAge = function (idx, newAge) {
const newData = [...data];
for (let d of newData) {
if (d.id === idx) {
d.age = newAge;
}
}
console.log(newData);
setdata(newData);
};
return (
<div className="App">
{data.map((d) => (
<ChildComponent
id={d.id}
name={d.name}
age={d.age}
updateAge={updateAge}
/>
))}
</div>
);
}
The child component looks like this:
import "./styles.css";
import { useState, useEffect } from "react";
export default function ChildComponent({ id, name, age, updateAge }) {
const [enableSave, setEnableSave] = useState(false);
const [showAgeInput, setShowAgeInput] = useState(false);
const [newAge, setNewAge] = useState(age);
const handleAgeClick = () => {
setShowAgeInput(true);
};
const handleAgeUpdate = () => {
updateAge(id, newAge);
};
const handleSaveEnable = () => {
setEnableSave(true);
};
return (
<>
<span>{name} </span>
<span
onClick={handleAgeClick}
style={{ display: showAgeInput ? "none" : "" }}
>
{" "}
{age}
</span>
<input
type="text"
onChange={(e) => setNewAge(e.target.value)}
style={{ display: showAgeInput ? "" : "none" }}
onBlur={handleSaveEnable}
/>
<button disabled={!enableSave} onClick={handleAgeUpdate}>
Save
</button>
</>
);
}
Now when I save button after clicking on Age span and updating its value, the re-rendering doesn’t happen due to which I don’t see the input gets hidden and button getting disabled.
I can see updateAge
function is called though which in turn should trigger setData and hence re-rendering? But the re-rendering doesn’t seem to happen.
What could be the reason?