The prop `history` is marked as required in `Router`, but its value is `undefined`. in Router

Mammad2c picture Mammad2c · Mar 24, 2017 · Viewed 69.5k times · Source

I am new to ReactJs. This is my code:

var React = require('react');
var ReactDOM = require('react-dom');
var {Route, Router, IndexRoute, hashHistory} = require('react-router');
var Main = require('Main');
ReactDOM.render(
  <Router history={hashHistory}>
  <Route path="/" component={Main}></Route>
</Router>, document.getElementById('app'));

and compiling it with webpack. Also I added Main component to my aliases. The console throws these errors: I also read these links :

React Router failed prop 'history', is undefined

How do I resolve history is marked required, when value is undefined?

Upgrading React-Router and replacing hashHistory with browserHistory

and many searches around the web, but I couldn't fix this issue. React Router is version 4

Answer

betomoretti picture betomoretti · Mar 30, 2017

If you are using react-router v4 you need to install react-router-dom as well. After that, import BrowserRouter from react-router-dom and switch Router for BrowserRouter. It seems that v4 change several things. Also, the react-router documentation is outdated. This is my working code:

import React from 'react';
import ReactDOM from 'react-dom';
import { BrowserRouter, Route } from 'react-router-dom'
import App from './components/App';

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

Source