Ads

React JS 12 - There are several ways to pass values from one component to another component

What is this mean?

Let's suppose we have two functional components, first component Product, second component Detail. The component Product wants to share data product id to component Detail.


Hello All,

Welcome to C# article, My Self Chakrapani Upadhyaya a full stack engineer.

In this article we will understand react concept that "Passing value to one component to another component".

In React JS, there are several ways to pass values from one component to another. 
Below are some common methods used in React JS:

Props: 

You can pass data from a parent component to a child component using props. To pass props, you simply add the data as attributes to the child component in the parent component's JSX. In the child component, you can access the data through the props object.

Example:

// Main component
function App() {
  const message = "Hello Last Bench Coder";
  return <AnotherComponent message={message} />;
}

// Another component
function AnotherComponent(props) {
  return <p>{props.message}</p>;
}

Context: 

Context allows you to pass data down the component tree without the need to pass props explicitly at every level. Context is a way to create a global state that can be accessed by any component in the application.

Example:


// Create a context
const MyContext = React.createContext();

// Parent component
function App() {
  const message = "Hello Last Bench Coder";
  return (
    <MyContext.Provider value={message}>
      <ChildComponent />
    </MyContext.Provider>
  );
}

// Child component
function ChildComponent() {
  const message = useContext(MyContext);
  return <p>{message}</p>;
}

State management libraries Like Redux: 

State management libraries like Redux and MobX provide a way to manage global state in a React application. With these libraries, you can create a global store that can be accessed by any component in the application.
Tags

Post a Comment

0 Comments
* Please Don't Spam Here. All the Comments are Reviewed by Admin.

#buttons=(Accept !) #days=(20)

Our website uses cookies to enhance your experience. Learn More
Accept !