-2

I am trying to route to a class component but it gives me an error. When I change the component to a functional component, the routing works. How do I route to class components?

I am new to using react-router. I first had a functional component to route to. But once I realized the component needs to be a class, I changed it to a class and now the routing shows

"Cannot GET /explore/words'.

index.js

import React from "react";
import { render } from "react-dom";
import { BrowserRouter } from "react-router-dom";
import App from "./App";

render(
  <BrowserRouter>
    <App />
  </BrowserRouter>,
  document.querySelector("#root")
);

App.js

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

import HomePage from "./pages/HomePage";
import ExplorePage from "./pages/ExplorePage";

function App() {
  return (
    <Router>
    <div>
      <header>
        <nav>Course Finder</nav>
      </header>
        <Route path="/" component={HomePage} />
        <Route path="/explore/:campus" component={ExplorePage} />
    </div>
    </Router>
  );
}

export default App;

Explore.js

import React, { Component } from "react";

class ExplorePage extends Component {
  render() {
    return (
      <div>
        <h1>Explore</h1>
      </div>
    );
  }
}

export default ExplorePage;

Expected result was to see the 'Explore' heading. I get 'Cannot GET /explore/words' instead.

ravibagul91
  • 20,072
  • 5
  • 36
  • 59
Justin
  • 1
  • 1
  • 1
  • 1
  • To be clear, with react-router-dom there is no requirement for a React component to be a class. Also keep mind there is a prop for Route called exact that is usually used with default/home route. – Alexander Staroselsky Aug 30 '19 at 03:30
  • Post your `HomePage` also where you have `Link` / navigation. – ravibagul91 Aug 30 '19 at 03:38
  • try this one if you are using webpack https://stackoverflow.com/questions/43209666/react-router-v4-cannot-get-url/43212553 – isuruAb Aug 30 '19 at 04:25
  • @isuruAb Thank you, this was my actual problem. I read it and learned about it here: https://tylermcginnis.com/react-router-cannot-get-url-refresh/ – Justin Aug 30 '19 at 05:30
  • @AlexanderStaroselsky Thanks! I thought it was and was scratching my head why would there be a component restriction. My issue was with missing config instructions for webpack! – Justin Aug 30 '19 at 05:31

1 Answers1

-1

This is working fine, all you have to do is add /explore/one to url to see the route working.

https://codesandbox.io/embed/nervous-wood-cw8cd

Jayraj
  • 390
  • 4
  • 16