136

I've been having some trouble with react router (i'm using version^4.0.0).

this is my index.js

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


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

  </Router>,
  document.getElementById('root')
);

the App.js is just anything. i'm posting the basic one here, cause it's not the problem (i believe)

import React, { Component } from 'react';
import logo from './logo.svg';
import './App.css';

class App extends Component {
  render() {
    return (
      <div className="App">
        <div className="App-header">
          <img src={logo} className="App-logo" alt="logo" />
          <h2>Welcome to React</h2>
        </div>
        <p className="App-intro">
          To get started, edit <code>src/App.js</code> and save to reload.
        </p>
      </div>
    );
  }
}

export default App;

and this is what happens when i check the console log

Router.js:43 Uncaught TypeError: Cannot read property 'location' of undefined
    at new Router (Router.js:43)
    at ReactCompositeComponent.js:295
    at measureLifeCyclePerf (ReactCompositeComponent.js:75)
    at ReactCompositeComponentWrapper._constructComponentWithoutOwner (ReactCompositeComponent.js:294)
    at ReactCompositeComponentWrapper._constructComponent (ReactCompositeComponent.js:280)
    at ReactCompositeComponentWrapper.mountComponent (ReactCompositeComponent.js:188)
    at Object.mountComponent (ReactReconciler.js:46)
    at ReactCompositeComponentWrapper.performInitialMount (ReactCompositeComponent.js:371)
    at ReactCompositeComponentWrapper.mountComponent (ReactCompositeComponent.js:258)
    at Object.mountComponent (ReactReconciler.js:46)

oh, and this is the package.json just in case

{
  "name": "teste2",
  "version": "0.1.0",
  "private": true,
  "dependencies": {
    "react": "^15.4.2",
    "react-dom": "^15.4.2",
    "react-router": "^4.0.0"
  },
  "devDependencies": {
    "react-scripts": "0.9.5"
  },
  "scripts": {
    "start": "react-scripts start",
    "build": "react-scripts build",
    "test": "react-scripts test --env=jsdom",
    "eject": "react-scripts eject"
  }
}

i've been checking this on other places, but i didn't find a way to solve it.

Thank you guys very much for your patience and help!!

Lucas fersa
  • 1,467
  • 2
  • 10
  • 8

7 Answers7

329

You're doing a few things wrong.

  1. First, browserHistory isn't a thing in V4, so you can remove that.

  2. Second, you're importing everything from react-router, it should be react-router-dom.

  3. Third, react-router-dom doesn't export a Router, instead, it exports a BrowserRouter so you need to import { BrowserRouter as Router } from 'react-router-dom.

Looks like you just took your V3 app and expected it to work with v4, which isn't a great idea.

Tyler McGinnis
  • 34,836
  • 16
  • 72
  • 77
  • 5
    That's kinda the case haha. i was learning from a course in Udemy and it used V3. I tried that, didn't work. I looked up some way to use it in V4 but all i could find was people telling me to dowgrade. that's how I ended up here. Anyway, thankyou very much for your help. I Really appreciate it :D – Lucas fersa Mar 20 '17 at 03:00
  • Hey Tyler, do you have any sample code for the same? – MohammedAshrafali May 23 '17 at 07:05
  • I have the same error in react-router in 4.1.1 after following these steps. Do I need to create a history object myself? – PDN Jun 08 '17 at 05:28
  • 1
    Thanks man! by reading your answer I found out I was having the error due to the react-router version. Since I couldn't find a good documentation for the v4, I decided to downgrade to V3 and then it started working for me as I wanted – sergioviniciuss Jun 10 '17 at 21:47
  • @TylerMcGinnis "react-router-dom doesn't export a Router" https://github.com/ReactTraining/react-router/blob/5342c9fd58c85fd0b6272a5f12dcedab7416c0fe/packages/react-router-dom/modules/BrowserRouter.js#L24-L25 react-router-dom is throwing this warning that says to use `Router`. – corysimmons Mar 30 '18 at 00:18
  • using all components correctly and not doing ```BrowserRouter as Router``` also gives this error. Thanks for that piece – Tharaka Devinda Apr 13 '20 at 07:41
  • what about v5 react-router – Shreyan Mehta Apr 18 '20 at 19:04
14

Replace

import { Router, Route, Link, browserHistory } from 'react-router';

With

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

It will start working. It is because react-router-dom exports BrowserRouter

Ajay P.
  • 455
  • 1
  • 6
  • 14
8

I've tried everything suggested here but didn't work for me. So in case I can help anyone with a similar issue, every single tutorial I've checked is not updated to work with version 4.

Here is what I've done to make it work

import React from 'react';
import App from './App';

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


 ReactDOM.render((
        <HashRouter>
            <div>
                <Route path="/" render={()=><App items={temasArray}/>}/>
            </div>
        </HashRouter >
    ), document.getElementById('root'));

That's the only way I have managed to make it work without any errors or warnings.

In case you want to pass props to your component for me the easiest way is this one:

 <Route path="/" render={()=><App items={temasArray}/>}/>
Roberto
  • 1,793
  • 1
  • 18
  • 19
  • I have a similar set up but on my landing page my first component shows up without ever clicking on the menu link. I will post a question Thanks – Si8 Jul 08 '19 at 15:44
2

location from the useLocation hook or from the useHistory hook is referencing the BrowserRouter from react-router-dom

So only call useLocation and useHistory from children components so this code below will work

#src/index.js

import React from "react";
import ReactDOM from "react-dom";
import "./index.css";
import App from "./App";
import { BrowserRouter,Switch, Route, } from "react-router-dom";

ReactDOM.render(
  <>
    <BrowserRouter>
      <Switch>
        <Route>
           <App />
        <Route>
      </Switch>   
    </BrowserRouter>
      </>,
      document.getElementById("root")
    );

then in your App.js you can get location by the useLocation hook or useHistory

since it's a child of the BrowserRouter it will be defined

eg. const { location} = useHistory(); eg. const loction = useLocation();

iamevansobeng
  • 435
  • 3
  • 7
0

so if you need want use this code )

import { useRoutes } from "./routes";

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

export const App = () => {

const routes = useRoutes(true);

  return (

    <Router>

      <div className="container">{routes}</div>

    </Router>

  );

};

// ./routes.js 

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

export const useRoutes = (isAuthenticated) => {
  if (isAuthenticated) {
    return (
      <Switch>
        <Route path="/links" exact>
          <LinksPage />
        </Route>
        <Route path="/create" exact>
          <CreatePage />
        </Route>
        <Route path="/detail/:id">
          <DetailPage />
        </Route>
        <Redirect path="/create" />
      </Switch>
    );
  }
  return (
    <Switch>
      <Route path={"/"} exact>
        <AuthPage />
      </Route>
      <Redirect path={"/"} />
    </Switch>
  );
};
whallz
  • 2,365
  • 2
  • 22
  • 24
vipdanek
  • 1
  • 1
  • 3
    hi, think about adding some infos about your code, explain what you did. – Gianmarco Nov 23 '20 at 00:22
  • I'm use router in folder with name routes you can see on the import in App.js , and I use in this code authentication, if isAuthenticated (). And I imparted functions use routers for App.js – vipdanek Nov 23 '20 at 13:09
  • 1
    edit you answer to allow users that read it to have a complete picture of the situation and the solution – Gianmarco Nov 23 '20 at 13:26
0
   appBar: {
    transition: theme.transitions.create(['margin', 'width'], {
      easing: theme.transitions.easing.sharp,
      duration: theme.transitions.duration.leavingScreen
    }),
    backgroundColor: '#fff' // add the styles here
  }

if you already have appBar at useStyles you can add the styles you just want.

mercury
  • 2,390
  • 3
  • 30
  • 39
0

It should be

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

Make sure they follow each other in that sequence. That works for me though

Suhaib Janjua
  • 3,538
  • 16
  • 59
  • 73
Adam Alex
  • 1
  • 3