0

Based on the isLoggedIn I need to route to different components.

I'm getting the login page but not able to render homepage.

{this.state.isLoggedIn ?
    (
      <Route
        path='/home'
        render={() => <HomePage  onLogout={this.onLogout} />}
      />
    )
    :
    (
      <Route exact path='/' component={() => <LoginPage onLogin={this.onLogin} />}/>
    )
}
piet.t
  • 11,035
  • 20
  • 40
  • 49
ReNinja
  • 375
  • 1
  • 5
  • 20

3 Answers3

2

You can redirect by rendering a <Redirect> will navigate to a new location. The new location will override the current location in the history stack, like server-side redirects (HTTP 3xx) do.

import { Route, Redirect } from 'react-router'

<Route exact path="/" render={() => (
  loggedIn ? (
    <Redirect to="/dashboard"/>
  ) : (
    <PublicHomePage/>
  )
)}/>

For pass prop by redirect

<Redirect to={{
    pathname: '/dashboard',
    state: { id: '123' }
}} />

Then you can access prop via this.props.location.state.id

Tung Duong
  • 988
  • 6
  • 17
  • how can i send the props to the components in this redirect – ReNinja Jan 29 '19 at 07:21
  • 1
    let me add more example in answer. @ReNinja I added example for passing props by redirect. please check – Tung Duong Jan 29 '19 at 07:23
  • where can I specify the component name Homepage – ReNinja Jan 29 '19 at 07:35
  • I think you can check this tutorial https://blog.pshrmn.com/entry/simple-react-router-v4-tutorial/ have return (
    ); so you can declare component for route, and redirect to that route
    – Tung Duong Jan 29 '19 at 07:39
  • Getting parsing error in the redirect `Line 36: Parsing error: Unexpected token, expected "," 34 | 36 | onLogout:{this.onLogout} | ^ 37 | }}/> 38 | ) : ( 39 | ` – ReNinja Jan 29 '19 at 08:36
  • I have tried the below code but the homepage is not rendering ` {this.state.isLoggedIn ? (
    } />
    ) : ( } />) }`
    – ReNinja Jan 29 '19 at 09:05
1

Use Redirect

From your parent component, pass this.state.isLoggedIn as props to LoginPage and HomePage component.

in LoginPage component

render(){
  if(this.props.isLoggedIn){
   return <Redirect to='/home' />
  }

  return ( your login page )
}

Do the same in your HomePage component with the Redirect's path '/'instead.

Peter
  • 179
  • 3
  • 9
  • Is it ok to redirect in the render() function ? And what is the difference between "" and "this.props.history.push('/home');" – mhlsf Mar 27 '19 at 10:48
  • 1
    Sorry for the late reply. Yeah, it is fine to redirect in render because is a react's component. The differences between those two are here: https://stackoverflow.com/a/54452810/10104154 – Peter May 06 '19 at 06:04
0

You can use this.props.history.push(myRoutes) and send route in the argument. It will redirect you to desired route.

Umair Farooq
  • 1,567
  • 10
  • 14