Deepak Bandi
Deepak Bandi

Reputation: 1904

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

Upvotes: 0

Views: 35

Answers (1)

Eliav Louski
Eliav Louski

Reputation: 5294

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>

}

Upvotes: 2

Related Questions