0
votes

I am trying to use the router object in child component but unable to do so. My main goal is to change the route after successful login. In react router v4 I can not use the history object directly.

My main goal is to use this.context.router so I cam make the route transition.

Here is my application code ( I stripped out most of them just added what I think is needed) If you need more information please comment.

Router

I have doubts about how I am adding components to route. But this is the only way I have found to use layout. So if you have any advice on this I will appreciate it.

<Router>
    <Switch>

        <Route path="/login" render={ () => ( <LayoutEmpty {...data} children={ <Login user={this.props.user} /> }  /> ) } />

        <Route exact path="/" render={ () => ( <LayoutApp {...data} children={ <Dashboard user={this.props.user} /> }  /> ) } />

        <Route path="*" component={LayoutNotFound} />

    </Switch>
</Router>

Now Lets just talk about the login component. Inside the component there is not context object passed.

I have added contextTypes like this

Login.contextTypes = {
  router: PropTypes.object
};

But that gives me only empty object as constant. Not route object is passed.

( let me know if you need code for login component but I think I have problem how I used <Route>)

1
See this to use nested route and routing dynamically stackoverflow.com/questions/44434041/…Shubham Khatri

1 Answers

0
votes

I have ended up refactoring my code and passing the history object down to the Smart component (container) level.

My Refactored router looks like this

<Router>
    <Switch>

        <Route path="/login" component={Login} />

        <Route exact path="/" component={Dashboard} />

        <Route path="*" component={LayoutNotFound} />

    </Switch>
</Router>

After that I am importing my Layout component to containers ( Login, Dashboard ) and pass down history object as a props to those containers if they are requiring it.

Container (Smart component)

import React from 'react';
import LayoutApp from '../containers/LayoutApp'

    class Dashboard extends React.Component{
    ...
    render(){   
            return (    
            <LayoutApp history={this.props.history} title="Dashboard">  
             ...