How to push to History in React Router v4?
Asked Answered
I

24

492

In the current version of React Router (v3) I can accept a server response and use browserHistory.push to go to the appropriate response page. However, this isn't available in v4, and I'm not sure what the appropriate way to handle this is.

In this example, using Redux, components/app-product-form.js calls this.props.addProduct(props) when a user submits the form. When the server returns a success, the user is taken to the Cart page.

// actions/index.js
export function addProduct(props) {
  return dispatch =>
    axios.post(`${ROOT_URL}/cart`, props, config)
      .then(response => {
        dispatch({ type: types.AUTH_USER });
        localStorage.setItem('token', response.data.token);
        browserHistory.push('/cart'); // no longer in React Router V4
      });
}

How can I make a redirect to the Cart page from function for React Router v4?

Incult answered 9/3, 2017 at 16:56 Comment(7)
Just to add to this from the last solution offered and from suggestions in React Router's issues on GitHub, using the context to pass what you need manually is a "no go". Unless I am a library author, there shouldn't be a need to use it. In fact, Facebook recommends against it.Incult
@Incult did you find a solution for this ? i need push to a different component in action , same as you have explained hereUnprepared
@Mr.G, sadly I have not. Last I read was the React Training team that maintains React Router has a redux package available. I haven't had any luck making it work, and they haven't put much work into resolving it.Incult
Why can't we use windows.location.href= URL? Is there anything wrong in using it to change the URL and redirect?Oklahoma
I don't see why not, but the option for using history also works for React Native as an option as well an addition option of supporting legacy browsers.Incult
@Oklahoma you would loose application state i believe if you location.href. also its is not mobile friendly.Arbiter
Using @Shan's suggestion ex., ( windows.location.href=("/") ) with zero issues on mobile. working as intended. *losing application state in my specific use case is a non issue.Naresh
T
406

You can use the history methods outside of your components. Try by the following way.

First, create a history object used the history package:

// src/history.js

import { createBrowserHistory } from 'history';

export default createBrowserHistory();

Then wrap it in <Router> (please note, you should use import { Router } instead of import { BrowserRouter as Router }):

// src/index.jsx

// ...
import { Router, Route, Link } from 'react-router-dom';
import history from './history';

ReactDOM.render(
  <Provider store={store}>
    <Router history={history}>
      <div>
        <ul>
          <li><Link to="/">Home</Link></li>
          <li><Link to="/login">Login</Link></li>
        </ul>
        <Route exact path="/" component={HomePage} />
        <Route path="/login" component={LoginPage} />
      </div>
    </Router>
  </Provider>,
  document.getElementById('root'),
);

Change your current location from any place, for example:

// src/actions/userActionCreators.js

// ...
import history from '../history';

export function login(credentials) {
  return function (dispatch) {
    return loginRemotely(credentials)
      .then((response) => {
        // ...
        history.push('/');
      });
  };
}

UPD: You can also see a slightly different example in React Router FAQ.

Tillery answered 23/8, 2017 at 21:32 Comment(13)
I have tried to do exactly as what @OlegBelostotsky said, but after history.push('some path'), the URL changes but the page does not change. I have to put window.location.reload() after it in some parts of my code just to make it work. However, in one instance I have to keep the redux state tree, and reloading destroys it. Any other solution?Encyclopedia
@idunno Try use the withRouter higher-order component.Tillery
This threw me an error stating: createBrowserHistory is not a function. What can i do?Stratum
@Stratum Maybe import createHistory from 'history/createBrowserHistory'; export default createHistory(); will be work.Tillery
I find it more logical to use a simple class with methods for route navigation than using the react-router components. Thanks for this solution!Hakim
not working for me. url got updated but component did not render.Dealer
I went through the below link and tried out the withRouter higher-order component.. but it didn't work for me.. link this solution provided by @OlegBelostotsky did the trickCoefficient
Sorry for the downvote :). While this should also work, the correct way to handle this is how Chris answered: https://mcmap.net/q/74143/-how-to-push-to-history-in-react-router-v4.Concertante
is the default behaviour, when you push something to the history, that you get immediately redirected to the last pushed route?Kalfas
I had similar problem every redirect was putting whole URL address instead of relative one. Just using createBrowserHistory(); not createBrowserHistory(#something here#); solved my issues!Dalmatic
react native web,side menu item click for refresh dashboard home,same like for react-native run android--this.props.navigation.navigate({ key: Math.random() * 10000, routeName: "DashBoard", params: id}) same this from web app.Sciamachy
make sure you are using the correct version of history as indicated in the docs. I had a similar issue as @Encyclopedia (url pushed to history but page doesn't change) when using history v5 with react router v5. Downgrading history to v4 solved the issue entirely.Dishrag
Upvoted comment by @Dishrag because this is the correct answer to the question posed/implied: how to access history outside of any React component However, you have to use history v4 with react-router v5 or history v5 with react-router v6, otherwise it will seem like nothing is working.Rawalpindi
I
390

React Router v4 is fundamentally different from v3 (and earlier) and you cannot do browserHistory.push() like you used to.

This discussion seems related if you want more info:

  • Creating a new browserHistory won't work because <BrowserRouter> creates its own history instance, and listens for changes on that. So a different instance will change the url but not update the <BrowserRouter>.
  • browserHistory is not exposed by react-router in v4, only in v2.

Instead you have a few options to do this:

  • Use the withRouter high-order component

    Instead you should use the withRouter high order component, and wrap that to the component that will push to history. For example:

    import React from "react";
    import { withRouter } from "react-router-dom";
    
    class MyComponent extends React.Component {
      ...
      myFunction() {
        this.props.history.push("/some/Path");
      }
      ...
    }
    export default withRouter(MyComponent);
    

    Check out the official documentation for more info:

    You can get access to the history object’s properties and the closest <Route>'s match via the withRouter higher-order component. withRouter will re-render its component every time the route changes with the same props as <Route> render props: { match, location, history }.


  • Use the context API

    Using the context might be one of the easiest solutions, but being an experimental API it is unstable and unsupported. Use it only when everything else fails. Here's an example:

    import React from "react";
    import PropTypes from "prop-types";
    
    class MyComponent extends React.Component {
      static contextTypes = {
        router: PropTypes.object
      }
      constructor(props, context) {
         super(props, context);
      }
      ...
      myFunction() {
        this.context.router.history.push("/some/Path");
      }
      ...
    }
    

    Have a look at the official documentation on context:

    If you want your application to be stable, don't use context. It is an experimental API and it is likely to break in future releases of React.

    If you insist on using context despite these warnings, try to isolate your use of context to a small area and avoid using the context API directly when possible so that it's easier to upgrade when the API changes.

Incult answered 10/3, 2017 at 10:26 Comment(12)
Yes I did try it. Thanks for asking. :-) So how do you get the context into this action function? So far, it's coming up as undefined.Incult
I have been researching this topic for a few days now and have not been able to get this to work. Even using the example above I keep getting router is undefined in the context. I am currently using react v15.5.10, react-router-dom v4.1.1, prop-types 15.5.10. The documentation around this is sparse and not very clear.Daube
@Daube this should work this.context.router.history.push('/path');Haematite
I believe @MichaelHorogjanski's answer is correct, especially since React's team states not to use context for stability reasons.Adroit
@Adroit correct. This is already stated at the bottom of my answer. Hence why I have 2 methods posted ;)Incult
@Incult Indeed, if you try to instantiate history object and use it by yourself it will change the url but will not render component - as you mentioned above. But, how to use "history.push" outside of the component and force component render as well?Penates
This doesn't answer the question being asked which is how to access history.push OUTSIDE of a component. Using withRouter or the context are not options for when outside of a component.Threedecker
why does PropTypes.object have to be specified? I thought PropTypes were only for future developers?Peraza
context API now officially supported by React; so is it safe to use now ?Hydrotherapeutics
Its a shame React Router has the name "react" in it. Leads people to think its the official router.Needlepoint
As of React 16.3 the context API isn't experimental anymore. React's blog post React v16.3.0: New lifecycles and context API for more info on the release.Leandro
I'dd like to add that this approach also makes the component easier to test, since it's not tight coupled to the global browserHistory api, and it relies on the api passed by props, which can easily be mocked/stubbed/spied on.Concertante
P
121

Now with react-router v5 you can use the useHistory hook like this:

import { useHistory } from "react-router-dom";

function HomeButton() {
  let history = useHistory();

  function handleClick() {
    history.push("/home");
  }

  return (
    <button type="button" onClick={handleClick}>
      Go home
    </button>
  );
}

read more at: https://reacttraining.com/react-router/web/api/Hooks/usehistory

Phylum answered 24/10, 2019 at 7:59 Comment(6)
Is there any specific way I need to set this up, I'm calling the following let history = useHistory(); but getting an Object is not callable error, when I tried seeing what useHistory is console.log(useHistory) it shows up as undefined. using "react-router-dom": "^5.0.1"Unifoliate
@Unifoliate you need to update it in yout package.json file to "react-router-dom": "^5.0.1" and run 'npm install'Phylum
Nice, but can't use hook inside redux action classes as they are not React component/functionHardtack
How would you use this for redirection upon login using (async). Here's the question => #62154908Vannie
To quote React: "Hooks can only be called inside of the body of a function component."Basalt
Check if there is <Router> tag inside of the component you're calling useHistory(). If it does, move <Router> tag to index.js instead (wrapping from parent component). Why ? I don't know. It seems like an issue of the library. @UnifoliateAllocate
N
44

Simplest way in React Router 4 is to use

this.props.history.push('/new/url');

But to use this method, your existing component should have access to history object. We can get access by

  1. If your component is linked to Route directly, then your component already has access to history object.

    eg:

    <Route path="/profile" component={ViewProfile}/>
    

    Here ViewProfile has access to history.

  2. If not connected to Route directly.

    eg:

    <Route path="/users" render={() => <ViewUsers/>}
    

    Then we have to use withRouter, a heigher order fuction to warp the existing component.

    Inside ViewUsers component

    • import { withRouter } from 'react-router-dom';

    • export default withRouter(ViewUsers);

    That's it now, your ViewUsers component has access to history object.

UPDATE

2- in this scenario, pass all route props to your component, and then we can access this.props.history from the component even without a HOC

eg:

<Route path="/users" render={props => <ViewUsers {...props} />}
Nynorsk answered 24/12, 2018 at 18:13 Comment(3)
Excellent! Your second method also did the trick for me, as my component (which needs access to this.props.history) comes from a HOC, which means that it is not directly linked to the Route, as you explain.Ming
Note that when you use history.push, the second argument is the state (see reactrouter.com/web/api/history). For my case, I did history.push('/same/route/I/am/currently/on', this.state) right after an operation that updated the state. That causes the new state to get added to the history stack. Then in compoenntDidMount() I check if this.props.location.state is defined, and if it is, call this.setState(this.props.location.state) to bring back the state when I get back to my component.Savory
this doesn't answer the original question how to use history outside a componentGriffith
L
27

This is how I did it:

import React, {Component} from 'react';

export default class Link extends Component {
    constructor(props) {
        super(props);
        this.onLogout = this.onLogout.bind(this);
    }
    onLogout() {
        this.props.history.push('/');
    }
    render() {
        return (
            <div>
                <h1>Your Links</h1>
                <button onClick={this.onLogout}>Logout</button>
            </div>
        );
    }
}

Use this.props.history.push('/cart'); to redirect to cart page it will be saved in history object.

Enjoy, Michael.

Luckett answered 12/4, 2017 at 21:3 Comment(2)
Yes, it looks like within the components you can push just fine. The only way to affect navigating outside a component is with redirect.Incult
This doesn't answer the question being asked which is how to access history.push OUTSIDE of a component. Using this.props.history is not an option for when outside of a component.Threedecker
N
23

According to React Router v4 documentation - Redux Deep Integration session

Deep integration is needed to:

"be able to navigate by dispatching actions"

However, they recommend this approach as an alternative to the "deep integration":

"Rather than dispatching actions to navigate you can pass the history object provided to route components to your actions and navigate with it there."

So you can wrap your component with the withRouter high order component:

export default withRouter(connect(null, { actionCreatorName })(ReactComponent));

which will pass the history API to props. So you can call the action creator passing the history as a param. For example, inside your ReactComponent:

onClick={() => {
  this.props.actionCreatorName(
    this.props.history,
    otherParams
  );
}}

Then, inside your actions/index.js:

export function actionCreatorName(history, param) {
  return dispatch => {
    dispatch({
      type: SOME_ACTION,
      payload: param.data
    });
    history.push("/path");
  };
}
Northrop answered 13/8, 2017 at 23:51 Comment(0)
B
19

Nasty question, took me quite a lot of time, but eventually, I solved it this way:

Wrap your container with withRouter and pass history to your action in mapDispatchToProps function. In action use history.push('/url') to navigate.

Action:

export function saveData(history, data) {
  fetch.post('/save', data)
     .then((response) => {
       ...
       history.push('/url');
     })
};

Container:

import { withRouter } from 'react-router-dom';
...
const mapDispatchToProps = (dispatch, ownProps) => {
  return {
    save: (data) => dispatch(saveData(ownProps.history, data))}
};
export default withRouter(connect(mapStateToProps, mapDispatchToProps)(Container));

This is valid for React Router v4.x.

Bombproof answered 28/10, 2017 at 23:6 Comment(1)
Thanks, your withRouter solution works with typescript but its quite slow compared with earlier import { createBrowserHistory } from 'history' any idea please?Hardtack
F
9

I offer one more solution in case it is worthful for someone else.

I have a history.js file where I have the following:

import createHistory from 'history/createBrowserHistory'
const history = createHistory()
history.pushLater = (...args) => setImmediate(() => history.push(...args))
export default history

Next, on my Root where I define my router I use the following:

import history from '../history'
import { Provider } from 'react-redux'
import { Router, Route, Switch } from 'react-router-dom'

export default class Root extends React.Component {
  render() {
    return (
     <Provider store={store}>
      <Router history={history}>
       <Switch>
        ...
       </Switch>
      </Router>
     </Provider>
    )
   }
  }

Finally, on my actions.js I import History and make use of pushLater

import history from './history'
export const login = createAction(
...
history.pushLater({ pathname: PATH_REDIRECT_LOGIN })
...)

This way, I can push to new actions after API calls.

Hope it helps!

Foliar answered 30/10, 2017 at 12:15 Comment(0)
A
7

this.context.history.push will not work.

I managed to get push working like this:

static contextTypes = {
    router: PropTypes.object
}

handleSubmit(e) {
    e.preventDefault();

    if (this.props.auth.success) {
        this.context.router.history.push("/some/Path")
    }

}
Arnulfoarny answered 18/5, 2017 at 8:25 Comment(1)
This doesn't answer the question being asked which is how to access history.push OUTSIDE of a component. Using this.context is not an option for when outside of a component.Threedecker
H
7

Be careful that don't use [email protected] or [email protected] with [email protected]. URL will update after history.push or any other push to history instructions but navigation is not working with react-router. use npm install [email protected] to change the history version. see React router not working after upgrading to v 5.

I think this problem is happening when push to history happened. for example using <NavLink to="/apps"> facing a problem in NavLink.js that consume <RouterContext.Consumer>. context.location is changing to an object with action and location properties when the push to history occurs. So currentLocation.pathname is null to match the path.

Hipped answered 2/1, 2021 at 10:17 Comment(0)
P
6

In this case you're passing props to your thunk. So you can simply call

props.history.push('/cart')

If this isn't the case you can still pass history from your component

export function addProduct(data, history) {
  return dispatch => {
    axios.post('/url', data).then((response) => {
      dispatch({ type: types.AUTH_USER })
      history.push('/cart')
    })
  }
}
Paillasse answered 9/8, 2017 at 9:4 Comment(0)
O
5

I struggled with the same topic. I'm using react-router-dom 5, Redux 4 and BrowserRouter. I prefer function based components and hooks.

You define your component like this

import { useHistory } from "react-router-dom";
import { useDispatch } from "react-redux";

const Component = () => {
  ...
  const history = useHistory();
  dispatch(myActionCreator(otherValues, history));
};

And your action creator is following

const myActionCreator = (otherValues, history) => async (dispatch) => {
  ...
  history.push("/path");
}

You can of course have simpler action creator if async is not needed

Obsequent answered 13/12, 2020 at 12:52 Comment(1)
It's great. Thanks so muchDanielledaniels
B
4

If you are using Redux, then I would recommend using npm package react-router-redux. It allows you to dispatch Redux store navigation actions.

You have to create store as described in their Readme file.

The easiest use case:

import { push } from 'react-router-redux'

this.props.dispatch(push('/second page'));

Second use case with Container/Component:

Container:

import { connect } from 'react-redux';
import { push } from 'react-router-redux';

import Form from '../components/Form';

const mapDispatchToProps = dispatch => ({
  changeUrl: url => dispatch(push(url)),
});

export default connect(null, mapDispatchToProps)(Form);

Component:

import React, { Component } from 'react';
import PropTypes from 'prop-types';

export default class Form extends Component {
  handleClick = () => {
    this.props.changeUrl('/secondPage');
  };

  render() {
    return (
      <div>
        <button onClick={this.handleClick}/>
      </div>Readme file
    );
  }
}
Bizerte answered 24/7, 2017 at 13:26 Comment(1)
This does not work with react-router-redux unless you are using the next version, which is still under development at this moment!Matthaus
M
4

Here's my hack (this is my root-level file, with a little redux mixed in there - though I'm not using react-router-redux):

const store = configureStore()
const customHistory = createBrowserHistory({
  basename: config.urlBasename || ''
})

ReactDOM.render(
  <Provider store={store}>
    <Router history={customHistory}>
      <Route component={({history}) => {
        window.appHistory = history
        return (
          <App />
        )
      }}/>
    </Router>
  </Provider>,
  document.getElementById('root')
)

I can then use window.appHistory.push() anywhere I want (for example, in my redux store functions/thunks/sagas, etc) I had hoped I could just use window.customHistory.push() but for some reason react-router never seemed to update even though the url changed. But this way I have the EXACT instance react-router uses. I don't love putting stuff in the global scope, and this is one of the few things I'd do that with. But it's better than any other alternative I've seen IMO.

Mulligatawny answered 18/8, 2017 at 22:54 Comment(0)
E
4

I was able to accomplish this by using bind(). I wanted to click a button in index.jsx, post some data to the server, evaluate the response, and redirect to success.jsx. Here's how I worked that out...

index.jsx:

import React, { Component } from "react"
import { postData } from "../../scripts/request"

class Main extends Component {
    constructor(props) {
        super(props)
        this.handleClick = this.handleClick.bind(this)
        this.postData = postData.bind(this)
    }

    handleClick() {
        const data = {
            "first_name": "Test",
            "last_name": "Guy",
            "email": "[email protected]"
        }

        this.postData("person", data)
    }

    render() {
        return (
            <div className="Main">
                <button onClick={this.handleClick}>Test Post</button>
            </div>
        )
    }
}

export default Main

request.js:

import { post } from "./fetch"

export const postData = function(url, data) {
    // post is a fetch() in another script...
    post(url, data)
        .then((result) => {
            if (result.status === "ok") {
                this.props.history.push("/success")
            }
        })
}

success.jsx:

import React from "react"

const Success = () => {
    return (
        <div className="Success">
            Hey cool, got it.
        </div>
    )
}

export default Success

So by binding this to postData in index.jsx, I was able to access this.props.history in request.js... then I can reuse this function in different components, just have to make sure I remember to include this.postData = postData.bind(this) in the constructor().

Emprise answered 21/11, 2017 at 16:40 Comment(0)
T
4

so the way I do it is: - instead of redirecting using history.push, I just use Redirect component from react-router-dom When using this component you can just pass push=true, and it will take care of the rest

import * as React from 'react';
import { Redirect } from 'react-router-dom';
class Example extends React.Component {
  componentDidMount() {
    this.setState({
      redirectTo: '/test/path'
    });
  }

  render() {
    const { redirectTo } = this.state;

    return <Redirect to={{pathname: redirectTo}} push={true}/>
  }
}
Taft answered 1/4, 2019 at 6:29 Comment(1)
this is the correct which does not break react render cycleSchaaff
T
3

Use Callback. It worked for me!

export function addProduct(props, callback) {
  return dispatch =>
    axios.post(`${ROOT_URL}/cart`, props, config)
    .then(response => {
    dispatch({ type: types.AUTH_USER });
    localStorage.setItem('token', response.data.token);
    callback();
  });
}

In component, you just have to add the callback

this.props.addProduct(props, () => this.props.history.push('/cart'))
Tillett answered 11/3, 2018 at 19:53 Comment(0)
P
2

React router V4 now allows the history prop to be used as below:

this.props.history.push("/dummy",value)

The value then can be accessed wherever the location prop is available as state:{value} not component state.

Pupa answered 30/11, 2018 at 19:24 Comment(1)
This doesn't answer the question being asked which is how to access history.push OUTSIDE of a component. Using this.props.history is not an option for when outside of a component.Battologize
L
2

As we have a history already included in react router 5, we can access the same with reference

import React from 'react';
import { BrowserRouter, Switch, Route } from 'react-router-dom';

function App() {
   const routerRef = React.useRef();
   const onProductNav = () => {
       const history = routerRef.current.history;
       history.push("product");
   }
return (
    <BrowserRouter ref={routerRef}>
        <Switch>
            <Route path="/product">
                <ProductComponent />
            </Route>
            <Route path="/">
                <HomeComponent />
            </Route>
        </Switch>
    </BrowserRouter>
)
}
Louis answered 8/8, 2021 at 7:3 Comment(1)
Thanks, it worked like charm.Swam
P
1

step one wrap your app in Router

import { BrowserRouter as Router } from "react-router-dom";
ReactDOM.render(<Router><App /></Router>, document.getElementById('root'));

Now my entire App will have access to BrowserRouter. Step two I import Route and then pass down those props. Probably in one of your main files.

import { Route } from "react-router-dom";

//lots of code here

//somewhere in my render function

    <Route
      exact
      path="/" //put what your file path is here
      render={props => (
      <div>
        <NameOfComponent
          {...props} //this will pass down your match, history, location objects
        />
      </div>
      )}
    />

Now if I run console.log(this.props) in my component js file that I should get something that looks like this

{match: {…}, location: {…}, history: {…}, //other stuff }

Step 2 I can access the history object to change my location

//lots of code here relating to my whatever request I just ran delete, put so on

this.props.history.push("/") // then put in whatever url you want to go to

Also I'm just a coding bootcamp student, so I'm no expert, but I know you can also you use

window.location = "/" //wherever you want to go

Correct me if I'm wrong, but when I tested that out it reloaded the entire page which I thought defeated the entire point of using React.

Pandemic answered 21/9, 2018 at 5:49 Comment(0)
S
1

Create a custom Router with its own browserHistory:

import React from 'react';
import { Router } from 'react-router-dom';
import { createBrowserHistory } from 'history';

export const history = createBrowserHistory();

const ExtBrowserRouter = ({children}) => (
  <Router history={history} >
  { children }
  </Router>
);

export default ExtBrowserRouter

Next, on your Root where you define your Router, use the following:

import React from 'react';       
import { /*BrowserRouter,*/ Route, Switch, Redirect } from 'react-router-dom';

//Use 'ExtBrowserRouter' instead of 'BrowserRouter'
import ExtBrowserRouter from './ExtBrowserRouter'; 
...

export default class Root extends React.Component {
  render() {
    return (
      <Provider store={store}>
        <ExtBrowserRouter>
          <Switch>
            ...
            <Route path="/login" component={Login}  />
            ...
          </Switch>
        </ExtBrowserRouter>
      </Provider>
    )
  }
}

Finally, import history where you need it and use it:

import { history } from '../routers/ExtBrowserRouter';
...

export function logout(){
  clearTokens();      
  history.push('/login'); //WORKS AS EXPECTED!
  return Promise.reject('Refresh token has expired');
}
Sajovich answered 5/7, 2019 at 0:58 Comment(0)
S
0

you can use it like this as i do it for login and manny different things

class Login extends Component {
  constructor(props){
    super(props);
    this.login=this.login.bind(this)
  }


  login(){
this.props.history.push('/dashboard');
  }


render() {

    return (

   <div>
    <button onClick={this.login}>login</login>
    </div>

)
Sayette answered 1/3, 2018 at 9:33 Comment(0)
N
0
/*Step 1*/
myFunction(){  this.props.history.push("/home"); }
/**/
 <button onClick={()=>this.myFunction()} className={'btn btn-primary'}>Go 
 Home</button>
Nikolaus answered 10/3, 2018 at 8:11 Comment(2)
No need for any imports !Nikolaus
While this code may answer the question, providing additional context regarding why and/or how this code answers the question improves its long-term value.Haswell
C
0

If you want to use history while passing a function as a value to a Component's prop, with react-router 4 you can simply destructure the history prop in the render attribute of the <Route/> Component and then use history.push()

    <Route path='/create' render={({history}) => (
      <YourComponent
        YourProp={() => {
          this.YourClassMethod()
          history.push('/')
        }}>
      </YourComponent>
    )} />

Note: For this to work you should wrap React Router's BrowserRouter Component around your root component (eg. which might be in index.js)

Celestial answered 18/5, 2020 at 18:53 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.