Craig
Craig

Reputation: 18684

react-router 4 and redirecting programmatically

I am trying to redirect a user to where he came from, when going to a Login component. For now, actually, I'd be happy just to redirect to a known url. In this case, '/dashboard'.

My application starts with an app.js and the routes are defined as:

render() {
        return (
            <div>
                <Router>
                    <div>
                    <Navbar />
                        <Route exact path='/' component={Home}  />
                        <Route path='/about' component={About} />
                        <Route path='/contact' component={Contact} />
                        <Route path="/login" component={Login} />
                        <Route path="/register" component={Register} /> 
                        <Route path="/profile" component={Profile} />
                        <Route path="/dashboard" component={Dashboard} />
                        <Route path="/accounts" component={AccountList} />
                        <Route path="/account" component={Account}/>
                    </div>
                </Router>
            </div>
        )
    }

I have navigated to Login, and the user has entered their credentials. I have validated against a WebAPI call, and have a success.. So I want to redirect.

I am doing this:

message = "Welcome, " + Auth.Auth.firstname();
history.push("/dashboard");

My imports for my login screen has:

import history from '../../helpers/history.js';

Where history.js is simply:

import createHistory from 'history/createHashHistory'
export default createHistory();

The push is executed, but the screen doesn't refresh. The URL simply updates to:

http://localhost:8080/login#/dashboard

If I click my 'Dashboard' nav button, the URL changes to:

http://localhost:8080/dashboard

and my screen loads the dashboard.

How should I be redirecting, problematically, when I need to?

Upvotes: 4

Views: 576

Answers (1)

Liam
Liam

Reputation: 6743

You need to warp up your component withRouter then usethis.props.history.push('/dashboard')

no need to import history from '../../helpers/history.js';

Read more about withRouter

You can get access to the history object's properties and the closest 's match via the withRouter higher-order component. withRouter will pass updated match, location, and history props to the wrapped component whenever it renders.

import React from "react";
import { withRouter } from "react-router-dom";

class AppA extends React.Component {
  componentDidMount(){
    setTimeout(()=>{
      this.props.history.push("/b");
    },1000)
  }
  render() {
    return (
      <div>
        <h1> Component A will redirect after 1 sec </h1>
      </div>
    )
  }
}
export default withRouter(AppA);

Edit kk8pj61y0o

Upvotes: 2

Related Questions