Search code examples
reactjsreact-propsreact-context

How can i pass useState value from child to parent


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

Solution

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