Home > Software design >  How can i pass useState value from child to parent
How can i pass useState value from child to parent

Time:11-15

I am having two child components where they have a separate state. Now I want to use the state in the two-child components and render it in the parent. how can I do it

function ChildA() {
  const [solutestate, setsolutestate] = useState("");
  return (
    <div>
      <Jsme
        height="300px"
        width="400px"
        options="oldlook,star"
        onChange={setsolutestate}
      />
    </div>
  );
}

const childB = () => {
  const [solventstate, setsolventstate] = useState("");

  return (
    <div>
      <Jsme
        height="300px"
        width="400px"
        options="oldlook,star"
        onChange={setsolventstate}
      />
    </div>
  );
};


function App() {
  return (
    <div className="App">
      <ChildA />
      <ChildB />

      <div>{solutestate}</div>
      <div>{solventstate}</div>
    </div>
  );
}

CodePudding user response:

you should save the state in the parent(called lifting the state up) and then pass down the setters to the children.

function ChildA({ setsolutestateA}) {
    return (
      <div>
        <Jsme
          height="300px"
          width="400px"
          options="oldlook,star"
          onChange={setsolutestateA}
        />
      </div>
    );
  }
  
  const childB = ({{ setsolutestateB}}) => {
    return (
      <div>
        <Jsme
          height="300px"
          width="400px"
          options="oldlook,star"
          onChange={setsolutestateB}
        />
      </div>
    );
  };
  
  
  function App() {
    const [solutestateA, setsolutestateA] = useState("");
    const [solutestateB, setsolutestateB] = useState("");

    return (
      <div className="App">
        <ChildA {...{setsolutestateA}}/>
        <ChildB {...{setsolutestateB}}/>
  
        <div>{solutestateA}</div>
        <div>{solutestateB}</div>
      </div>
    );
  }

CodePudding user response:

You should pass a function setting the state from your parent to child component, so the child can update the parent's state with the call of a function passed with props.

Ex: Parent:

function App() {
  const [solventstate, setsolventstate] = useState("");

  const sendDataToParent = (solventstate) => { // the callback. Use a better name
    setsolventstate(solventstate);
  }
 
  return (
    <div className="App">
      <ChildA sendDataToParent={sendDataToParent}/>
      <ChildB sendDataToParent={sendDataToParent}/>
    </div>
  );
};

Child:

const childB = ({sendDataToParent}) => {
  return (
    <div>
      <Jsme
        height="300px"
        width="400px"
        options="oldlook,star"
        onChange={sendDataToParent(solventstate)}
      />
    </div>
  );
}:
  • Related