Many ways to pass data between React components.

React is popular web framework used to develop modern web apps. As we know, in React, all the things load inside a single page. This saves additional loading time which multiple page web apps face. But Since we have to load multiple components in a single web page, we have to pass data between these components. How do we do this? We will find out here.

First of all we have to create a new React application. We will use create-react-app tool for that. So open your console, cd to the place where you would like to create your app. Then type:

npx create-react-app my-app

After my-app gets created, open my-app folder in any code editor like Visual Studio Code or Sublime Text. Go to src folder and open App.js . Delete everything inside it. Now we will learn the most common way in which you can pass data between React components.

The “most common” way (Using state and props)

Inside App.js, type the following code:

//App.js
import React, { Component } from 'react'
export class App extends Component {

  render() {
    return (
      <div>
        test
      </div>
    )
  }
}

export default App

Now create a new file inside src folder called Name.js . Inside this file, type:

//Name.js
import React, { Component } from 'react'
export class Name extends Component {

    render() {
        return (
            <div>
                This is my name:
            </div>
        )
    }
}

export default Name

In our project, App.js is the main single page which will load whenever we will run the web app. So, right now, Name.js is of no use as it is not connected in any way to App.js . So let us connect these files. So inside App.js, first we will import Name.js, then call the <Name/> component from the render() method of App.js in the following way.

//App.js
import React, { Component } from 'react'
import Name from './Name'

export class App extends Component {

  render() {
    return (
      <Name/>
    )
  }
}

export default App

If you will run this react app using npm start command, you will see the following output:

This is my name:

Basically what happened in the above code is, we called Name component inside render() method of App component. So when we run the app, App.js is rendered and thus, Name also gets rendered as it is called from inside of App component.

Suppose we define some data inside App.js .

//App.js
import React, { Component } from 'react'
import Name from './Name'

export class App extends Component {
  state = {
    name: "Benjamin Button"
  }
  render() {
    return (
      <Name/>
    )
  }
}

export default App

In the above code, we defined data called state inside App.js . Now in order to pass this data to Name.js, We will edit the <Name/> component inside render() method of App.js to:

<Name namedata = {this.state.name}/>

Now inside Name.js, we will pull out this data in the following manner:

//Name.js
export class Name extends Component {

    render() {
        return (
            <div>
                This is my name: {this.props.namedata}
            </div>
        )
    }
}

Here since we sent the data from App.js using the identifier namedata , Thus in order to pull this data out from inside Name.js, we used {this.props.namedata}

If you will run this app, the output will be the following:

This is my name: Benjamin Button

The new way: Using stateless functional React components

Now React has introduced functional components instead of class based components. Since these functional components are stateless, so we can’t pass state from one component to other as we did in class based components. To resolve this problem, React introduced hooks at React Conf October 2018 as a way to use state and side-effects in React function components.

Let us demonstrate the passing of data between function components. Inside App.js, clear everything. Now let us start creating App() function component .

//App.js
import Name from './Name';
import React, {useState} from 'react'

export function App(){
    const [name, setName] = useState("Benjamin Button");
    return <Name name={name}>;
}

In the above code, we imported {useState} hook from react library. Then we used this hook to create state called name. Initial value of state is set as “Benjamin Button”. Note that we can use setName to change the state value if we want to.

Now to fetch this state from Name.js, we can simply edit Name.js in the following way:

//Name.js
export default function Name(props) {
    return (
        <div>
            My name is : {props.name}
        </div>
    )
}

If you will run this app, The output will be:

My name is : Benjamin Button

Now let us explore the third way to pass data between components, i.e using Redux.

The Redux way to pass data between components.

Redux is a state management library used in combination with React. When we have to deal with large web apps, state management using previous methods becomes cumbersome. This is why Redux is used in such cases. In order to use redux, we have to define Store, Reducer and Action. A beginners tutorial for basics of redux can be found here. So, first of all, Let us create store. Inside src directory, create a file Store.js . Inside it, type the following code:

//Store.js
import { createStore } from 'redux';
import {reducer} from './Reducer';

export const store = createStore(reducer, 'No Name');

We can see that this file imports reducer from Reducer.js . But we haven’t created this reducer yet. So inside src, again create a new file called Reducer.js . Now add the following code to it:

//Reducer.js
export const reducer = function(state, action) {
    if (action.type === 'name') {
      return action.payload;
    }
    return state;
};

We will explain what this file does in a bit, but first let us create our Action as well. So again create a file called Action.js inside src, add the following code to it:

//Action.js
import {store} from './Store';

store.dispatch({ type: 'name', payload: 'Benjamin Button' });

export default store;

In this file, we can see that when we dispatch an action with type: 'name', then upon reaching the reducer (i.e Reducer.js ), it will return action.payload i.e ‘Benjamin Button’.

Now in App.js, we will call <Name/> as usual:

//App.js
import React from 'react'
import Name from './Name'

function App() {
  return (
    <div>
      <Name/>
    </div>
  )
}

export default App

Inside Name.js, we will then call the store exported by Action.js in the following way:

//Name.js
import React from 'react'
import store from './Action'

function Name(props) {
    return (
        <div>
            My name is: {store.getState()}
        </div>
    )
}

export default Name

As you can see above, we used store.getState() to fetch the current state of the store, i.e “Benjamin Button”. If you run this web app, the output, as expected will be:

My name is: Benjamin Button

That’s it. These are the multiple ways in which you can pass data between React components. Hope you liked the article. Comment in case of any doubts. Also check out my articles on medium and follow me on twitter. Also check out my other articles on this blog as well!

Leave a Reply

Your email address will not be published. Required fields are marked *