Skip to content
Advertisement

How do I pass data between React Functional Components?

Currently, I am trying to pass a specific piece of data, the user’s name, from one functional component, the <User/> component, to another, the <Profile /> component, when the user navigates to a certain page.

Here is my code:

User.js

JavaScript

UsersList.js

JavaScript

Feed.js

JavaScript

App.js

JavaScript

And here is the current <Profile /> page – I simply want to pass the user’s name, not the username, into a pair of <h1></h1> tags:

Profile.js

JavaScript

I appreciate any help or direction!

Advertisement

Answer

You have to use Redux. This is how I sloved it-

First install redux module: npm install react-redux

src/components/Profile.js

Map the user data which is in redux store using mapStateToProps function

JavaScript

/src/action.js

Here I have initialized all the user initial values, ideally the user data you will get from another system, in such case you will use Thunk or Saga for side effect operations

JavaScript

/src/reducer.js

I am simply passing all the user data to the state object

JavaScript

/src/components/User.js

JavaScript

/src/components/UsersList.js

Here we have to use both mapDispatchToProps and mapStateToProps so that dispatch action is executed on a load of the component via useEffect hook.

JavaScript

/src/App.js

Use the BrowserRouter to wrap around the different routes

JavaScript

/src/index.js

Finally, hook the store as a wrapper around App component so that all the components can use Redux store and that is done by Provider.

JavaScript

/src/store.js

JavaScript

And the final result

enter image description here

User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement