Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React router - undefined history

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 /

like image 736
TheMP Avatar asked Jan 04 '16 16:01

TheMP


People also ask

Why history is undefined In react?

Unfortunately, when you try to click the button inside of OtherComponent you will encounter TypeError: history is undefined with the stack trace pointing to the line which looks innocent. The problem is that you cannot use useHistory hook if your component was not rendered between Router tag and its closing.

Why match is undefined react router?

react-router-dom v5 If using RRDv5 if the match prop is undefined this means that BookScreen isn't receiving the route props that are injected when a component is rendered on the Route component's component prop, or the render or children prop functions.

Is useHistory deprecated?

The use of history and useHistory is deprecated and should be replaced with the useNavigate hook.


3 Answers

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
}
like image 147
Santosh Pillai Avatar answered Oct 20 '22 04:10

Santosh Pillai


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
like image 34
holms Avatar answered Oct 20 '22 04:10

holms


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

like image 1
Henrik Andersson Avatar answered Oct 20 '22 03:10

Henrik Andersson