React Router not found page showing up on all paths

I'm experimenting with a bit of React Routing, and I experienced a problem when I tried to make an error page, which occurs each time the users gets a 404 error, which prompts a message:

import React from "react";

const Error = props => {
    return(
        <div>
        <p>
            Path does not exist!
        </p>
        </div>
    )

}

export default Error;

I wrapped all my paths, with a switch statement, to only make it apply to the absolute paths.

class App extends Component {

  render() {
    return (
      <BrowserRouter>
    <Switch>
    <div>
      <Route exact path="/"   component={Home}  />
      <Route exact path="/about"  component={About} />
      <Route path="*" exact component={Error} />
      </div>
    </Switch>
    </BrowserRouter>
    );
  }
}

but know whenever I access a path, the Error component shows up.

But I since I wrap in a Switch component, and use exact, shouldn't the Error component only show up, whenever another path does not exist?

Upvotes: 1

Views: 1325

Answers (1)

Omar
Omar

Reputation: 3411

   <Switch>
      <Route exact path="/"   component={Home}  />
      <Route exact path="/about"  component={About} />
      <Route component={Error} />
    </Switch>

Do not add a path for error route.

Upvotes: 2

Related Questions