Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can update props in child component functional component?

Tags:

reactjs

I have a parent component and a child component.

  • The parent component sends data to the child.
  • The child modifies the value and the parent should see the change reflected.

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>
  );
}

1 Answers

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>
  );
}
like image 130
Quentin Avatar answered Oct 31 '25 11:10

Quentin



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!