I have a parent component and a child component.
But nevertheless there is something that I am not doing well because I do not understand the mechanisms of react well.
Parent component
function ParentComponent() {
var userName = "Didi";
return (
<div className="Parent">
<label>Parent - {userName}</label>
<ChildComponent userName={userName} />
</div>
);
}
Child component
function ChildComponent({ userName }) {
const handleChange = (e) => {
userName = e.target.value;
};
return (
<div className="ChildComponent">
<input type="text" defaultValue={userName} onChange={handleChange} />
<br />
<label>ChildComponent - {userName}</label>
</div>
);
}
React can't monitor free variables for changes. You need to store data in a state (or use some external system like Redux).
If you want to change the state from a different component, then you need to pass the function which changes it to the component.
function ParentComponent() {
const [userName, setUserName] = React.useState("Didi");
return (
<div className="Parent">
<label>Parent - {userName}</label>
<ChildComponent userName={userName} setUserName={setUserName} />
</div>
);
}
function ChildComponent({ userName, setUserName }) {
const handleChange = (e) => {
setUserName(e.target.value);
};
return (
<div className="ChildComponent">
<input type="text" defaultValue={userName} onChange={handleChange} />
<br />
<label>ChildComponent - {userName}</label>
</div>
);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With