Search code examples
reactjsreact-functional-component

Is it possible to pass data between 2 functional component in React?


I have two component in the same directory level. Home and Checkout. Without using Class, is it possible to pass the data between these 2 pages?

function Homepage() {
  const [question, setquestion] = useState("");
  ....
  ....
 return (
    <input value={question} onChange={(e) => setquestion(e.target.value)} type="text"/>
 )
}

Now, in the Checkout component, I need to access that value in question.

function Checkoutpage({ socket, props }) {
   const [question, setquestion] = ??? [How do I access question from previous page];
}

Solution

  • you should hold your useState in a common parent and pass it down to both Homepage and Checkoutpage

    function Homepage({question,setquestion}) {
        return (
            <input value={question} onChange={(e) => setquestion(e.target.value)} type="text"/>
        )
    }
    function Checkoutpage({ socket, props,question,setquestion }) {
        question, setquestion // accesisable here
        return ...
    }
    function CommonParent(props) {
        const [question, setquestion] =  useState("");
        
        return <div>
            <Homepage {...{question, setquestion}}/>
            <Checkoutpage {...{question, setquestion}}/>
        </div>
    
    }