React router - undefined history

37,409

Solution 1

As of "react-router": "^4.1.1", you may try the following:

Use 'this.props.history.push('/new-route')'. Here's a detailed example

1: Index.js

 import { BrowserRouter, Route, Switch } from 'react-router-dom'; 
 //more imports here
    ReactDOM.render(
      <div>
        <BrowserRouter>
           <Switch>
              <Route path='/login' component={LoginScreen} />
              <Route path='/' component={WelcomeScreen} />
           </Switch>
        </BrowserRouter>
     </div>, document.querySelector('.container'));

Above, we have used BrowserRouter, Route and Switch from 'react-router-dom'.

So whenever you add a component in the React Router 'Route', that is,

<Route path='/login' component={LoginScreen} />

..then 'React Router' will add a new property named 'history' to this component (LoginScreen, in this case). You can use this history prop to programatically navigate to other rountes.

So now in the LoginScreen component you can navigate like this:

2: LoginScreen:

return (
      <div>
       <h1> Login </h1>
       <form onSubmit={this.formSubmit.bind(this)} >
         //your form here
       </form>
      </div>

    );



formSubmit(values) {
 // some form handling action
   this.props.history.push('/'); //navigating to Welcome Screen
}

Solution 2

Because everything changes like hell in react world here's a version which worked for me at December 2016:

import React from 'react'
import { Router, ReactRouter, Route, IndexRoute, browserHistory } from 'react-router';

var Main = require('../components/Main');
var Home = require('../components/Home');
var Dialogs = require('../components/Dialogs');

var routes = (
    <Router history={browserHistory}>
        <Route path='/' component={Main}>
            <IndexRoute component={Home} />
            <Route path='/dialogs' component={Dialogs} />
        </Route>
    </Router>
);

module.exports = routes

Solution 3

To create browser history you now need to create it from the History package much like you've tried.

import createBrowserHistory from 'history/lib/createBrowserHistory';

and then pass it to the Router like so

<Router history={createBrowserHistory()}>
    <Route />
</Router>

The docs explain this perfectly

Share:
37,409
TheMP
Author by

TheMP

https://www.linkedin.com/in/marek-pasieka-b3931168

Updated on February 20, 2020

Comments

  • TheMP
    TheMP about 4 years

    I am trying to use the 1.0.0-rc1 react-router and history 2.0.0-rc1 to navigate manually through the website after pressing the button. Unfortunately, after pressing the button I get:

    Cannot read property 'pushState' of undefined

    My router code:

    import React from 'react';
    import { Router, Route, Link, browserHistory } from 'react-router'
    import AppContainer from './components/AppContainer.jsx';
    import MyTab from './components/test/MyTab.jsx';
    import MainTab from './components/test/MainTab.jsx';
    
    
    var routes = (
        <Route component={AppContainer} >
            <Route name="maintab" path="/" component={MainTab} />
            <Route name="mytab" path="/mytab" component={MyTab} />
        </Route>
    );
    
    React.render(<Router history={browserHistory}>{routes}</Router>, document.getElementById('main'));
    

    The navigation button is on MyTab and it attemps to navigate to MainTab:

    import React from 'react';
    import 'datejs';
    import History from "history";
    export default React.createClass({
    
        mixins: [ History ],
    
        onChange(state) {
            this.setState(state);
        },
    
        handleClick() {
            this.history.pushState(null, `/`)
        },
    
        render() {
            return (
                <div className='container-fluid' >
                    <button type="button" onClick={this.handleClick.bind(this)}>TEST</button>
                </div>
    
            );
        }
    });
    

    When I use history with this.props.history everything works fine. What is the problem with this code?

    EDIT.

    After adding the following:

    const history = createBrowserHistory();
    
    React.render(<Router history={history}>{routes}</Router>, document.getElementById('main'));
    

    I try to access my app. Before (without history={history}), I just accessed localhost:8080/testapp and everything worked fine - my static resources are generated into dist/testapp directory. Now under this URL I get:

    Location "/testapp/" did not match any resources

    I tried to use the useBasename function in a following way:

        import { useBasename } from 'history'
        const history = useBasename(createBrowserHistory)({
        basename: '/testapp'
    });
    
    React.render(<Router history={history}>{routes}</Router>, document.getElementById('main'));
    

    and the application is back, but again I get the error

    Cannot read property 'pushState' of undefined

    in the call:

    handleClick() {
        this.history.pushState(null, `/mytab`)
    },
    

    I thougt it may be because of my connect task in gulp, so I have added history-api-fallback to configuration:

    settings: {
          root: './dist/',
          host: 'localhost',
          port: 8080,
          livereload: {
            port: 35929
          },
          middleware: function(connect, opt){
            return [historyApiFallback({})];
          }
        }
    

    But after adding middleware all I get after accessing a website is:

    Cannot GET /

  • Venkat.R
    Venkat.R over 8 years
    Please add those other history types createHashHistory, createBrowserHistory,createMemoryHistory
  • TheMP
    TheMP over 8 years
    @limelights I tried your suggestion and updated the question. Could you have a look at it?
  • Henrik Andersson
    Henrik Andersson over 7 years
    @holms It worked at the time of writing, react-router has undergone significant changes since january :)
  • Marián Zeke Šedaj
    Marián Zeke Šedaj about 7 years
    Type 'History' is not assignable to type 'History' -- closes laptop
  • Chris Noreikis
    Chris Noreikis almost 7 years
    Just tried this solution with React Router 4.1.1. 'history/lib/createBrowserHistory' wasn't working for me, but I was able to import 'history/createBrowserHistory'.
  • Henrik Andersson
    Henrik Andersson almost 7 years
    @ChrisNoreikis They probably changed it since a year ago. :)