passing data between components in react js

Passing Data Between Components in React JS

If you are working on a React project with multiple components, you might need to pass data between them at some point. There are several ways to pass data between components in React JS. Let's explore some of the commonly used methods:

1. Props

In React, you can pass data from a parent component to a child component using props. Props are read-only and cannot be modified by the child component. To pass props, you need to define them in the parent component and then use them in the child component.


  // Parent Component
  
  import React from 'react';
  import ChildComponent from './ChildComponent';

  const ParentComponent = () => {
    const name = "Raju";
    return <ChildComponent name={name} />;
  }

  // Child Component

  import React from 'react';

  const ChildComponent = (props) => {
    return <h3>Hello {props.name}!</h3>;
  }
  

2. Context

Context provides a way to pass data through the component tree without having to pass props down manually at every level. It is designed to share data that can be considered "global" for a tree of React components.


  // Creating Context

  import React from 'react';

  const MyContext = React.createContext();

  // Parent Component

  const ParentComponent = () => {
    const name = "Raju";
    return (
      <MyContext.Provider value={name}>
        <ChildComponent />
      </MyContext.Provider>
    );
  }

  // Child Component

  const ChildComponent = () => {
    const name = React.useContext(MyContext);
    return <h3>Hello {name}!</h3>;
  }
  

3. State Management Libraries

If you have a large and complex application, you might consider using state management libraries like Redux or MobX to manage your data. These libraries provide a centralized store where you can store and retrieve data from any component in your application.


  // With Redux

  import { connect } from 'react-redux';

  const ParentComponent = ({ name }) => {
    return <ChildComponent name={name} />;
  }

  const mapStateToProps = state => ({
    name: state.name
  });

  export default connect(mapStateToProps)(ParentComponent);

  // With MobX

  import { observer, inject } from 'mobx-react';

  const ParentComponent = ({ store }) => {
    const { name } = store;
    return <ChildComponent name={name} />;
  }

  export default inject('store')(observer(ParentComponent));
  

In conclusion, there are multiple ways to pass data between components in React JS. Depending on your project requirements and complexity, you can choose the best method that suits your needs.

Subscribe to The Poor Coder | Algorithm Solutions

Don’t miss out on the latest issues. Sign up now to get access to the library of members-only issues.
[email protected]
Subscribe