Home > Software design >  How to pass data from different functional component?
How to pass data from different functional component?

Time:09-23

I am new to React and I am using functional components and I have 5 functional components. What I want to do is to get all the data from all the functional components to the very last component when the user clicks on submit.

CodePudding user response:

You could check this out React Context Api.

As per their docs, Context provides a way to pass data through the component tree without having to pass props down manually at every level.

Or if you think this would be too much trouble, you could lift up your state to the nearest common ancestor and then pass them as props. (I think this is more trouble).

For this, you could check this out State Lifting

CodePudding user response:

There are multiple ways to do it. It depends on your application size. If your app will be small so you can use React Context API's or mobx for managing the state.

If your application is large so I suggest use redux for managing a global state.

If you don't want to use any other library you can be archiving that stuff in React inbuild via managing the state. But for that, you need to pass a value as props in your child component.

import React from "react";
import PropTypes from "prop-types";

/**
 * Component for showing details of the user.
 *
 * @component
 * @example
 * const age = 21
 * const name = 'Jitendra Nirnejak'
 * return (
 *   <User age={age} name={name} />
 * )
 */
const User = (props) => {
  const { name, age } = props;
  return (
    <p>
      {name} is {age} years old.
    </p>
  );
};

User.propTypes = {
  /**
   * User's name
   */
  name: PropTypes.string.isRequired,
  /**
   * User's age
   */
  age: PropTypes.number,
};

User.defaultProps = {
  text: "Asif Vora",
  age: 21,
};

export default User;

Use the child component in the parent.

import React from "react";
import User from "./User";

const Parent = () => {
  return (
    <User name="abc" age={15} />
  );
};

export default Parent;
  • Related