React-router - How to pass data between pages in React?

JavascriptReactjsReact Router

Javascript Problem Overview


I am working on a project where I have to pass data from one page to another. For example, I have data on the first page.

let data = [
  {id:1, name:'Ford', color:'Red'},
  {id:2, name:'Hyundai', color:'Blue'}
]

Here is the first component page where I render this list of data with the name.

class ListDetail extends Component {
    constructor();
    handleClick(data){
    console.log(data);
  }
  render() {
    return (
      <div>
        <Hello name={this.state.name} />
        <ul>
          {data.map((data,i) => {
            return <li onClick={this.handleClick.bind(this,data)}>{data.name}</li>
          })}
        </ul>
      </div>
    );
  }
}

I want to pass this data to the next page where I need this data and more data than this. I am using React Router 4. Any suggestion or help would be helpful.

Javascript Solutions


Solution 1 - Javascript

You can use the Link component from react-router and specify to={} as an object where you specify pathname as the route to go to. Then add a variable e.g. data to hold the value you want to pass on. See the example below.

Using the <Link /> component:

<Link
  to={{
    pathname: "/page",
    state: data // your data array of objects
  }}
>

Using history.push()

this.props.history.push({
  pathname: '/page',
    state: data // your data array of objects
})

Using either of the above options you can now access data on the location object as per the below in your page component.

render() {
  const { state } = this.props.location
  return (
    // render logic here
  )
}

You can see an example of how to pass a value along with a route in another example here.

Solution 2 - Javascript

Best way to pass data to the target Component, just copy paste the code and see the magic, I also explained it in depth.


Remember: in react-router-dom v6 you can use hooks instead.

version 5.X

Let's suppose we have two Components first and second. The first has the link which will target the second component.

The first Component where the link is, by clicking the link you will go to the target path as in my case it is:"/details".

import React from 'react';
import {Link} from 'react-router-dom';

export default function firstComponent() {
return(
<>
    <Link to={{
      pathname: '/details',
      state: {id: 1, name: 'sabaoon', shirt: 'green'}
    }} >Learn More</Link>
</>
)
}

Now in the second Component you can access the passed object as:

import React from 'react'


export default class Detials extends React.Component{

    constructor(props){
        super(props);
        this.state={
            value:this.props.location.state,
        }

    }


alertMessage(){
       console.log(this.props.location.state.id);
    }

render(){
return (

    <>
     {/* the below is the id we are accessing */}

      hay! I am detail no {this.props.location.state.id} and my name is 
      {this.props.location.state.name}

      <br/>
      <br/>

 {/* press me to see the log in your browser console */}
<button onClick={()=>{this.alertMessage()}}>click me to see log</button>

    </>

    )
}

}

note:In version 6 of react-router-dom the above method won't work on class components though you can use functional components of react by using useLocation hook and then you can draw the state object through that location in another component.


version 6

How to achieve the same using hooks v6 of react-router-dom

Let's suppose we have two functional components, first component A, second component B. The component A wants to share data to component B.

usage of hooks: (useLocation,useNavigate)

import {Link, useNavigate} from 'react-router-dom';

function ComponentA(props) {

  const navigate = useNavigate();

  const toComponentB=()=>{
navigate('/componentB',{state:{id:1,name:'sabaoon'}});
  }

  return (
   <>
<div> <a onClick={()=>{toComponentB()}}>Component B<a/></div>
</>
  );


}


export default ComponentA;

Now we will get the data in Component B.

import {useLocation} from 'react-router-dom';

 function ComponentB() {

    const location = useLocation();
   
        return (

            <>
               
<div>{location.state.name}</div>

            </>
        )
    }

export default ComponentB;

Solution 3 - Javascript

You can use react-router's Link component and do the following:

<Link to={{
  pathname: '/yourPage',
  state: [{id: 1, name: 'Ford', color: 'red'}]
}}> Your Page </Link>

and then access the data with this.props.location.state

You could also consider using redux for state management in your whole application (https://redux.js.org/).

Solution 4 - Javascript

how to pass data into another compoent router in reactjs

Login.jsx

 handleClickSignIn(){
            console.log("come handle click fun");
            this.props.history.push( {pathname: "/welcome",
            state: { employee:"Steven" }});
      
        }

welcome.jsx

componentDidMount()
{
  console.log(this.props.location.state.employee);
}

Solution 5 - Javascript

Assuming your other page is a component you could pass the data as a prop which will be available on the next page. Something to note though, you must use <Link /> component which available in react-router 4 as opposed to using <a></a> which causes a full page reload hence making access of the data lost.

Solution 6 - Javascript

When you want to send one page in one object same code below you must import your page in your object file and again import your page in your destination file same this:

import Home from './componenets/home/home';
import ColdDrink from './componenets/coldDrink/coldDrink';
import HotDrink from './componenets/hotDrink/hotDrink';
import CheaseCake from './componenets/cheaseCake/cheaseCake';
import Lost from './componenets/404/lost';

const link = [
{
name   : "Cold Drink",
link   : "/ColdDrink",
router : <ColdDrink/>
},
{
name   : "Hot Drink",
link   : "/HotDrink",
router : <HotDrink/>
},
{
name   : "chease Cake",
link   : "/CheaseCake",
router : <CheaseCake/>
},
{
name   : "Home",
link   : "/",
router : <Home/>
},
{
name   : "",
link   : "",
router : <Lost/>
}
];

and in your destination file you must map your object...

const links = (this.props.link);
{links.map((item, i) => (
  {item.router}
))}

Solution 7 - Javascript

State data, current data is on the Checkout.tsx page, and pass state data on the App.tsx page (using typescript)

Checkout.tsx page
 import { useHistory } from 'react-router-dom';
 export default function CheckoutPage() {
    const history = useHistory();
    const data = [
    {
      name: "Ngoc",
      id: 1
    },
    {
      name: "Kevin",
      id: 2
    },
    {
      name: "Jack",
      id: 3
    },
  ];

   history.push({
    pathname: `/app`, /* this path field is based on your project */
    state: data ? data : [] /* pass state data to app page */,
  });
}
App.tsx page
 import { useLocation } from 'react-router-dom';
 export default function AppPage() {
    const history = useHistory();
    // use useLocation read data form Checkout page
    const location = useLocation<any>();
    const currentDataFromCheckoutPage = location.state;
    // data pass show here
    console.log('currentDataFromCheckoutPage', currentDataFromCheckoutPage);
}

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionAndrewView Question on Stackoverflow
Solution 1 - JavascriptRoy ScheffersView Answer on Stackoverflow
Solution 2 - JavascriptSabaoon BedarView Answer on Stackoverflow
Solution 3 - JavascriptrieckpilView Answer on Stackoverflow
Solution 4 - JavascriptSoma sundaraView Answer on Stackoverflow
Solution 5 - JavascriptDennis WanjiruView Answer on Stackoverflow
Solution 6 - JavascriptOmid MoghadasView Answer on Stackoverflow
Solution 7 - JavascriptNgocDuongView Answer on Stackoverflow