Gaurav Kandpal
Gaurav Kandpal

Reputation: 1330

Getiing error TypeError: history is undefined while using React-router

I am new in React. As I am start working with routes in react I faced a error which is TypeError: history is undefined.

My code are.

import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import Login from './components/login/Login';
import registerServiceWorker from './registerServiceWorker';
import { Router, Route, browserHistory } from 'react-router'

ReactDOM.render(
  <Router history={browserHistory}>
    <Route path="/" component={App}>

    </Route>
    <Route path="/login" component={Login} />
  </Router>
  ,
  document.getElementById('root')
);
registerServiceWorker();

Upvotes: 0

Views: 1286

Answers (3)

Paolo Guerra
Paolo Guerra

Reputation: 259

Which version of react-router / react are you using? Since version 4 of RR the browserHistory is imported with BrowserRouter. So for example you could do something like this:

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

ReactDOM.render(
    <Router history={browserHistory}>
        <Route path="/" component={App} />
        <Route path="/login" component={Login} />
    </Router>,
    document.getElementById('root')
);

registerServiceWorker();

And it should work well. See this for more information.

Upvotes: 0

vitomadio
vitomadio

Reputation: 1140

check your react version, I think browserHistory does not work with version 4, you'll have to use 'react-router-dom' instead and import BrowserRouter, then set your route like this:

<BrowserRouter>
    <Switch>
        <Route exact path="/" render={props => <App {...props} /> } />
        <Route path="/login" render={props => <Login {...props} /> } />
    </Switch>
</BrowserRouter>

Hope it helps.

Upvotes: 2

Kyaw Siesein
Kyaw Siesein

Reputation: 725

If that is react router v4, you are not doing it right.

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

ReactDOM.render(
  <BrowserRouter>
    <Route path="/" component={App} />
    <Route path="/login" component={Login} />
  </BrowserRouter>
  ,
  document.getElementById('root')
);

then from your component you can access history prop like this.

const App = props => {
console.log(this.props.history);
return <div>App</div>
};

Upvotes: 0

Related Questions