1

I am new to React.I am trying to change the route inside a function.I am used react-router-dom for routing.I used "react-router-dom": "^4.1.1".The function is,

 LogIn(email, password){

            this.props.LogInAction(email, password);
            if(this.props.loginstatus == true){

                    /* Here I need to go to '/home' */

            }
sojan
  • 67
  • 1
  • 10
  • Possible duplicate of [How to navigate dynamically using react router dom](https://stackoverflow.com/questions/44137774/how-to-navigate-dynamically-using-react-router-dom) – Mayank Shukla Jul 05 '17 at 11:24

2 Answers2

1

You can import withRouter on page like this:

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

And then use this to make redirection as:

if(this.props.loginstatus == true){
    this.props.history.push('/home');
}

And don't forget to declare withRouter while exporting class as:

export default withRouter(className);
CharlieBrown
  • 4,143
  • 23
  • 24
Triyugi Narayan Mani
  • 3,039
  • 8
  • 36
  • 56
  • It leads to an error for me. `./src/component/login.js 51:4-18 'react-router' does not contain an export named 'browserHistory'` – sojan Jul 05 '17 at 11:17
  • @sojan Do you have react-router installed? – Triyugi Narayan Mani Jul 05 '17 at 11:22
  • 1
    @sojan `import { browserHistory } from 'react-router-dom';` – Val Berthe Jul 05 '17 at 11:24
  • @TriyugiNarayanMani yes , I installed. And version is `"react-router": "^4.1.1` – sojan Jul 05 '17 at 11:29
  • @TriyugiNarayanMani I imported `import { BrowserRouter } from 'react-router-dom'`. and I used `BrowserRouter.push('/home');` for route. A new error `Uncaught TypeError: __WEBPACK_IMPORTED_MODULE_6_react_router_dom__.a.push is not a function` – sojan Jul 05 '17 at 11:55
  • @TriyugiNarayanMani `import { BrowserRouter } from 'react-router-dom'; ' browserHistory.push('/home');` results an error `./src/component/login.js Line 28: 'browserHistory' is not defined no-undef Search for the keywords to learn more about each error.` – sojan Jul 05 '17 at 12:29
1

If you use react-router, inside you class

pushHistory() {
        this.props.history.push("/");
    }

LogIn(email, password){

            this.props.LogInAction(email, password);
            if(this.props.loginstatus == true){

                   this.props.history.push("/");

            }

and your routes wrapped like this:

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

    <BrowserRouter>
                <div>
                    <Switch>
                    <Route exact={true} path="/" component={ App }/>
                    <Route exact path="/users" component={ UserList }/>
                    <Route exact path="/user/new" component={ UserCreate }/>
                    <Route path="/users/:id" component={ UserDetail }/>
                    </Switch>
                </div>
            </BrowserRouter>
Evgeniy Volk
  • 626
  • 5
  • 7