Reputation: 21
How is the initial state preserved when you you route to another component?
Say you have an e-commerce site, where you have information about a user's cart when the user is in checkout. Now the user decided to go to the main page. How will the cart information passed so that it is not lost?
Upvotes: 0
Views: 51
Reputation: 5862
Hi I guess the main page is the parent component and card page is the child component. It it is then you can pass the function reference from parent to child and pass child information to the parent by calling that function. here is the example:
Parent Component
import React, {useEffect, useState} from 'react';
import Child from "./Child";
function CParent(props) {
const [status, setStatus] = useState(false);
function setOpeningValue(status) {
console.log(status);
setStatus(status);
}
return (
<div>
<Child setOpeningValue={setOpeningValue}/>
</div>
);
}
export default CParent;
Child Component
import React, {useEffect, useState} from 'react';
// Child to Parent communication
function Child(props) {
const {setOpeningValue} = props;
const [isOpen, setOpen] = useState(false);
function clickHandler() {
setOpen(!isOpen);
setOpeningValue(`changes is ${!isOpen}`);
}
return (
<div>
<button onClick={clickHandler}>Open</button>
</div>
);
}
export default Child;
Upvotes: 1