Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the simplest way to pass state while using React Router?

What is the simplest way to pass state while using React Router? My Navi component below is reflecting user being null, as opposed to user being "KungLoad". Thanks.

class App extends Component{
  constructor() {
    super();
    this.state = {user: "KungLoad"};
}
  render () {
    return(
    <div>
<Router> 
    <Route exact path="/" state  component = {Navi} />
  </Router>

2 Answers

The simplest way is that you can pass the state as props and then use it in the specified component. For your case, you have to use render instead of component for passing the state as props.

<Route exact path="/" render={() => <Navi user={this.state.user} />}  />

This will work but I would recommend to you that the Context API concept of reactJS would be best suited here. You can pass the state or props to all the component using the data provider and all the components will consume the state or props that are being provided by the parent component. . https://reactjs.org/docs/context.html

like image 106
Subrato Pattanaik Avatar answered Oct 26 '25 05:10

Subrato Pattanaik


version 6 react-router-dom

I know the question got answered but I feel this might be helpful example for those who want to use functional components and they are in search of passing data between components using react-router-dom v6.

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;

Note: you can use HOC if you are using class components as hooks won't work in class components.

like image 43
Sabaoon Bedar Avatar answered Oct 26 '25 05:10

Sabaoon Bedar



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!