lmngn23
lmngn23

Reputation: 521

Pass data to other components in React-router

Hi I have the following routes for Login and Home component:

<Route exact path="/" name="Login Page" component={Login} />
<Route path="/home" name="Home" component={Home} />

The Login component uses react-final-form to submit user's input to the back-end and then go to Home like this

onSave = async (values) => {

 const user = await Api.postURL("/register", values);
 window.location.href = '/home';
}

How would I pass user's data from the back-end to Home component to later display it?

I would really appreciate any help

Upvotes: 0

Views: 464

Answers (1)

ravibagul91
ravibagul91

Reputation: 20755

The simple way is localStorage.

onSave = async (values) => {
   const user = await Api.postURL("/register", values);
   localStorage.setItem("user",JSON.stringify(user));
   window.location.href = '/home';
}

And in your Home component,

class Home extends React.Component{
  render(){
     const user = JSON.parse(localStorage.getItem("user"));
     return(
        ...
     );
  }
}

Another way is using Redirect from react-router-dom package.

import { Redirect } from 'react-router-dom'


onSave = async (values) => {
   const user = await Api.postURL("/register", values);
   <Redirect to={{
         pathname: '/home',
         state: { user:  JSON.stringify(user)}
     }}
   />
}

And in your Home component,

class Home extends React.Component{
  render(){
     const user = JSON.parse(this.props.location.state.user);
     return(
        ...
     );
  }
}

Upvotes: 2

Related Questions