amba patel
amba patel

Reputation: 424

TypeError: Cannot read property 'location' of undefined in react

I am creating a simple React application, and while implementing Routing I get following error:

TypeError: Cannot read property 'location' of undefined in react.

App.js:

import React, { Component } from 'react';
import logo from './logo.svg';
import './App.css';
import Header from "./components/header";
import Home from "./components/Home";
import About from "./components/About";
import Contact from "./components/Contact";
import { Router, Route} from 'react-router'

class App extends Component {
  render() {
    return (
      <div className="App">
      <Header />

   <Router>
      <Route path = "/" component = {App}>
         <Route path = "home" component = {Home} />
         <Route path = "about" component = {About} />
         <Route path = "contact" component = {Contact} />
      </Route>
   </Router>
        <header className="App-header">
          <img src={logo} className="App-logo" alt="logo" />
          <p>

            Edit <code>src/App.js</code> and save to reload.
          </p>
          <a  className="App-link"  href="https://reactjs.org"target="_blank"  rel="noopener noreferrer">
            Learn React
          </a>
        </header>
      </div>
    );
  }
}

export default App;

What am I missing here?

Upvotes: 0

Views: 11215

Answers (1)

TechSavy
TechSavy

Reputation: 1340

The problem here seems to be with import of router package.

install: npm install --save react-router-dom

Import the package in your App.js as:

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

And now modify your App.js render() function as-

 return (
  <BrowserRouter>
      <div className="App">
      <Header />

        <Route exact path = "/" component = {Home} />
        <Route path = "about" component = {About} />
        <Route path = "contact" component = {Contact} />


      <header className="App-header">
        <img src={logo} className="App-logo" alt="logo" />
        <p>

          Edit <code>src/App.js</code> and save to reload.
        </p>
        <a  className="App-link"  href="https://reactjs.org"target="_blank"  rel="noopener noreferrer">
          Learn React
        </a>
      </header>
    </div>
  </BrowserRouter>
);

Upvotes: 4

Related Questions