Passing Object Data from Child to Parent Component in React and Leveraging its Functionality

After performing a date calculation, I stored the values of year, month, and day in an object. Now, my goal is to send this object to the parent component App.js, and then pass that data to another child component named Modal.js as a prop. I want to display the calculation result in a popup message within the modal. However, I'm facing challenges in using and storing the received data in the App.js component.

UserAgeForm.js

const onSubmitHandler = (e) => {
    e.preventDefault();
    const calculateAge = () => {
        let calculatedYear;
        let calculatedMonth;
        let calculatedDay;

        if (currentDate < birthDay || currentMonth < birthMonth) {
            calculatedDay = currentDate + currentMonthDays - birthDay;
            calculatedMonth = currentMonth + 11 - birthMonth;
            calculatedYear = currentYear - 1 - birthYear;
        } else {
            calculatedDay = currentDate - birthDay;
            calculatedMonth = currentMonth - birthMonth;
            calculatedYear = currentYear - birthYear;
        }
        props.userData = {
            calculatedYear,
            calculatedMonth,
            calculatedDay,
        };
    };
    calculateAge();
};

App.js

function App() {
    const receivedUserData = {};
    const allUserData = {};
    return (
        <>
            <UserAgeForm userData={receivedUserData} />
            {ReactDOM.createPortal(
                <Modal resultData={allUserData} />,
                document.getElementById("modal")
            )}
        </>
    );
}

Answer №1

To manage the state in the App component, you can define a state variable and pass it along with the necessary callbacks as props to child components. This approach is commonly referred to as Lifting State Up.

Here's an example:

function App() {
  const [userData, setUserData] = React.useState({});

  return (
    <>
      <UserAgeForm setUserData={setUserData} />
      {ReactDOM.createPortal(
        <Modal resultData={userData} />,
        document.getElementById("modal")
      )}
    </>
  );
}

UserAgeForm Component:

const onSubmitHandler = (e) => {
  e.preventDefault();
  let calcYear;
  let calcMonth;
  let calcDay;

  if (currentDate < birthDay || currentMonth < birthMonth) {
    // perform calculations
    calcDay = currentDate + currentMonthDays - birthDay;
    calcMonth = currentMonth + 11 - birthMonth;
    calcYear = currentYear - 1 - birthYear;
  } else {
    // perform calculations
    calcDay = currentDate - birthDay;
    calcMonth = currentMonth - birthMonth;
    calcYear = currentYear - birthYear;
  }
        
  props.setUserData({
    calcYear,
    calcMonth,
    calcDay,
  });
};

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Instead of using <div>, try substituting it with a different HTML page

Seeking assistance on an HTML page project that involves jQuery, CSS, and HTML without server-side integration. Encountering an issue when attempting to replace a <div> with content from another HTML file saved on my computer. The main page code sni ...

Every time I try to restart my React Project, it seems to encounter strange issues that

Currently, I am following a fullstack React tutorial which you can find here: React Tutorial I have encountered an issue where every time I close my laptop and reopen the project, npm start throws a strange error. Initially, I tried to fix it by starting ...

The input type '{}' does not match the expected type 'Readonly<IIdeasContainerProps>'. The property '...' is not found in the type '{}'

Having recently started using TypeScript, I'm encountering some issues when attempting to execute this code snippet. Error The error message reads as follows: Failed to compile 13,8): Type '{}' is not assignable to type 'Readonly &l ...

What could be causing my React useState not to update my components?

My understanding of React might be lacking, but I am facing an issue with updating a Component after the state has been asynchronously updated. const [appState, setAppState] = useState({ countries: null, languages: null }) useEffect(() ...

Does type conversion have a specific ranking of preference?

When working with JavaScript, it's important to note that the language automatically converts types when necessary. For instance, if you have an expression like "8" * "3", JavaScript will convert the strings to numbers and calculate the result as 24. ...

Having trouble updating the URL path with the $location service in Angular

I'm facing a challenge in updating the URL path using the $location.url service, as it's not reflecting the changes correctly. For instance, my current URL path is http://localhost:64621/module/commercial/#/company/98163780-4fa6-426f-8753-e05a6 ...

Ways to swap out element within ViewContainerRef in Angular

I am currently expanding my knowledge of Angular and I have encountered a challenge regarding dynamically creating components and swapping them within a single container. Here is the setup: <ng-container #container></ng-container> Here are the ...

How can I access the values of FormData on the server-side?

Is it possible to send FormData from the front end to the backend in order to manage its values? For example, consider the following code snippet: onFormSubmit = async (event) => { event.preventDefault(); const { imageFile, currentGroupId } = ...

Incorporate PHP form and display multiple results simultaneously on a webpage with automatic refreshing

I am currently in the process of designing a call management system for a radio station. The layout I have in mind involves having a form displayed in a div on the left side, and the results shown in another div on the right side. There are 6 phone lines a ...

Tips for retrieving the value of an input field using Material-UI

Currently, I am implementing Material-UI within a React project. render(){return ( <input type="range" min="0" max="100" value="100" onChange={this.handleMasterVolume} class="master-gain form-control ...

Experiencing Troubles with Design Customization in Flowbite-React

I'm currently diving into the world of theme customization with Flowbite-React by following their guide on creating a reusable component with a custom theme. Unfortunately, I seem to be encountering some difficulties in getting it to function properly ...

Utilizing API calls within a loop using AngularJS

I need to execute a series of APIs in a loop, but I want the second loop to start only after receiving the result from the last API call in the first loop. How can I achieve this? for(var i=0; i<array.length; i++ ) service.getfunction(array[i]).t ...

Tips for simulating localStorage in TypeScript unit testing

Is there a method to simulate localStorage using Jest? Despite trying various solutions from this post, none have proven effective in TypeScript as I continue encountering: "ReferenceError: localStorage is not defined" I attempted creating my ...

Adding li elements dynamically, how can we now dynamically remove them using hyperlinks?

Please refrain from using jQuery code, as my main focus is on learning javascript. I am currently experimenting with adding li items dynamically to a ul when a button on the HTML page is clicked. Here's a sample implementation: HTML: <ul id="myL ...

What is the best technique for creating a preloader that can seamlessly fill the background of a vector image?

I am looking for guidance on creating a CSS3 preloader using a vector image. My goal is to have the logo start off transparent with only the border visible, and as the loading occurs, fill in from bottom to top with the background color. Thank you to ever ...

Conceal the parent div from its sibling within the same parent container

My goal is to conceal a parent component from its child element. I attempted to achieve this by using the parent component as a background while adding additional backgrounds to the child elements for overriding purposes. However, this method did not work ...

Tips for utilizing the randomColor library

Looking for guidance on incorporating the randomColor package from yarn to assign colors to various columns in a table within my project. Any examples or resources would be greatly appreciated! I am specifically working with React and Typescript. ...

Generate a sequence of years without relying on the range function

Is there a different approach to generating this array without relying on the range function? Below is an illustration of what I want, but without utilizing the range method. const years = myCustomArrayGeneration(1990, getYear(new Date()) + 1, 1); ...

Looking to set up a React build pipeline in VSTS using Yarn but struggling to locate the package.json file?

I am working on a React project and during local testing, I usually use commands like yarn install, yarn build, and yarn start to check it at https://localhost:3000 I have set up the following pipeline: However, when checking the logs, I encountered this ...

Updating JSON when the color changes in Go.js can be achieved by implementing event listeners and

I've been using Go.js for creating Flow charts and saving the json data into a SQL database. However, I'm facing difficulties in updating the json data. Here is the code snippet: myDiagram.addDiagramListener("ChangedSelection", function (e1) { ...