Thiagz
Thiagz

Reputation: 131

BrowserHistory never gets initialized in ReactJS

I'm very new to ReactJS. I was trying some tutorials to do routing but end up with errors where the "browserHistory" was undefined. The code and error message is as below.

Main.js

'use strict';

import React from 'react';
import ReactDOM from 'react-dom';
import { Router, Route, Link, IndexRoute, hashHistory,browserHistory} from 'react-router';
import App from './App.jsx';
import {Home,About,Contact} from './App.jsx';


ReactDOM.render((
   <Router history = {browserHistory}>
      <Route path = "/" component = {App}>
         <IndexRoute component = {Home} />
         <Route path = "home" component = {Home} />
         <Route path = "about" component = {About} />
         <Route path = "contact" component = {Contact} />
      </Route>
   </Router>

), document.getElementById('app'))

Error Message from browser console

Warning: Failed prop type: The prop history is marked as required in Router, but its value is undefined.in Router

Kindly let me know if the implementation is out-of-date or if I have missed out any libraries to face this problem

Upvotes: 1

Views: 532

Answers (3)

Crazy Psychild
Crazy Psychild

Reputation: 592

React Router v4 changed things. They made separate top level router elements. Replace <Router history={hashHistory}> with <HashRouter> in your code.

import {HashRouter,Route} from 'react-router-dom';

<HashRouter>
    <Route path = "/" component = {App} />
</HashRouter>

Upvotes: 0

Abhijith Sasikumar
Abhijith Sasikumar

Reputation: 14980

Can you try useRouterHistory:

import { useRouterHistory } from 'react-router';
import createBrowserHistory from 'history/lib/createBrowserHistory';

const createAppHistory = useRouterHistory(createBrowserHistory);

const history = createAppHistory({
 parseQueryString: parse,
 stringifyQuery: stringify
})

<Router history={history}/>

Upvotes: 0

Thiagz
Thiagz

Reputation: 131

I think I have found the reason, the new react-router does not support browserHistory anymore. To achieve the same goal I have used the following code.

import createBrowserHistory from 'history/createBrowserHistory';

const history = createBrowserHistory();

Upvotes: 1

Related Questions