I made a date calculation and I stored year, month & day values in an object and I wanna send this object to the parent App.js and then send that data to my other child component Modal.js as a prop and show it in the popup message (the calculation result) but while receiving the data in the App.js I don’t know how to use it / store it and send it to the other component.
UserAgeForm.js
const onSubmitHandler = (e) => {
e.preventDefault();
const calcAge = () => {
let calcYear;
let calcMonth;
let calcDay;
if (currentDate < birthDay || currentMonth < birthMonth) {
calcDay = currentDate + currentMonthDays - birthDay;
calcMonth = currentMonth + 11 - birthMonth;
calcYear = currentYear - 1 - birthYear;
} else {
calcDay = currentDate - birthDay;
calcMonth = currentMonth - birthMonth;
calcYear = currentYear - birthYear;
}
// 👇 here I'm trying to send the data
props.userData = {
calcYear,
calcMonth,
calcDay,
};
};
calcAge();
};
App.js
function App() {
const receivedUserData = {
// how to do it
};
const allUserData = {
// how to do it
};
return (
<>
<UserAgeForm userData={receivedUserData} />
{ReactDOM.createPortal(
<Modal resultData={allUserData} />,
document.getElementById("modal")
)}
</>
);
}
>Solution :
Declare some state in App to hold the state value and pass the state and callbacks to update it down as props to children. This pattern is commonly known as Lifting State Up.
Example:
function App() {
const [userData, setUserData] = React.useState({});
return (
<>
<UserAgeForm setUserData={setUserData} />
{ReactDOM.createPortal(
<Modal resultData={userData} />,
document.getElementById("modal")
)}
</>
);
}
UserAgeForm
const onSubmitHandler = (e) => {
e.preventDefault();
let calcYear;
let calcMonth;
let calcDay;
if (currentDate < birthDay || currentMonth < birthMonth) {
calcDay = currentDate + currentMonthDays - birthDay;
calcMonth = currentMonth + 11 - birthMonth;
calcYear = currentYear - 1 - birthYear;
} else {
calcDay = currentDate - birthDay;
calcMonth = currentMonth - birthMonth;
calcYear = currentYear - birthYear;
}
props.setUserData({
calcYear,
calcMonth,
calcDay,
});
};