23

I created the component NotFound and it works fine when I go to a page that doesn't exist. But the same page it's appearing in all my pages, not only the one that doesn't exist. This is the component:

import React from 'react'

const NotFound = () =>
  <div>
    <h3>404 page not found</h3>
    <p>We are sorry but the page you are looking for does not exist.</p>
  </div>

export default NotFound

And this is how I used it in the main page:

class MainSite extends Component {
  render () {
    return (
      <div>
        {/* Render nav */}
        <Route path='/dashboard' component={Nav} />
        <Route path='/retrospectives' component={Nav} />
        <Route path='/users' component={Nav} />
        <Route path='/projects' component={Nav} />

        {/* Dashboard page */}
        <ProtectedRoute exact path='/dashboard' component={DashboardPage} />

        {/* Retrospectives page */}
        <ProtectedRoute exact path='/retrospectives' component={RetrospectivesPage} />

        {/* Users page */}
        <ProtectedRoute exact path='/users' component={UsersPage} />

        {/* Projects page */}
        <ProtectedRoute exact path='/projects' component={ProjectsPage} />

        {/* Retrospective related pages */}
        <Route exact path='/retrospectives/:retrospectiveId' component={Retrospective} />
        <Route exact path='/join-retrospective' component={JoinRetrospective} />
        <ProtectedRoute exact path='/create-retrospective/:retrospectiveId' component={Retrospective} />

        {/* OnBoarding pages */}
        <ProtectedRoute exact path='/beta-code' component={BetaCodeAccess} />
        <Route exact path='/auth-handler' component={AuthHandler} />
        <Route exact path='/join-organization' component={JoinOrganization} />
      </div>
    )
  }
}

export default MainSite

As you can see I use <Route path="*" component={NotFound} /> to create the 404 pages, but that component is appearing in every existing page as well. How can I fix this?

Lizz Parody
  • 1,705
  • 11
  • 29
  • 48
  • 4
    Use a Switch tag to wrap your routes. That way only one route gets rendered. Also, place your not found Route on the very bottom of the routes and remove the path attribute. – Eduardo Rocha Mar 08 '18 at 20:18

7 Answers7

30

Try this one:

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

  <Switch>
    <Route path='/dashboard' component={Nav} />
    <Route path='/retrospectives' component={Nav} />
    <Route path='/users' component={Nav} />
    <Route path='/projects' component={Nav} />

    <Route path="" component={NotFound} />
  </Switch>
sultan
  • 4,543
  • 2
  • 24
  • 32
9

All below example works fine:

<Route path="" component={NotFound} /> // empty ""
<Route path="*" component={NotFound} /> // star *
<Route component={NotFound} /> // without path

Or if you want to return a simple 404 message without any component:

<Route component={() => (<div>404 Not found </div>)} />
Pedram
  • 15,766
  • 10
  • 44
  • 73
6

For those who are looking for an answer using react-router-dom v6, many things had changed. Switch for example doesn't exists anymore, you have to use element instead of component, ... Check this little example to get you an idea:

import React from 'react'
import ReactDOM from 'react-dom'
import { BrowserRouter as Router, Routes, Route } from 'react-router-dom'

import './index.css'
import App from './App'

const Test = () => (
  <h1>404</h1>
)

ReactDOM.render(
  <React.StrictMode>
    <Router>
      <Routes>
        <Route path='/' element={<App />} />
        <Route path='*' element={<Test />}/>
      </Routes>
    </Router>
  </React.StrictMode>,
  document.getElementById('root')
)

With this you are defining your home route and all the other routes will show 404. Check the official guide for more info.

Anthony Luzquiños
  • 739
  • 11
  • 23
2

Try This:

import React from "react";
import { Redirect, Route, Switch, BrowserRouter } from 'react-router-dom';
import HomePage from './pages/HomePage.jsx';
import NotFoundPage from './NotFoundPage.jsx';
class App extends React.Component {
    render(){
        return(
            <BrowserRouter>
                <Switch>
                    <Route exact path='/' component={HomePage} />
                    <Route path="*" component={NotFoundPage} />
                </Switch>
            </BrowserRouter>
        )
    }
}
   
export default App;
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
Ali Chraghi
  • 613
  • 6
  • 16
2

Simply import Switch from react-router-dom and wrap all your Routes in the Switch Component. Also Important here is to note to keep your 404Page component at the very bottom(just before your switch ending tag) This way it will match each component with its route first. If it matches, it will render the component or else check the next one. Ultimately if none matching routes will be founded, it will render 404Page

Kaustubh
  • 373
  • 1
  • 3
  • 14
0

react router is a headache for new coders. Use this code format. This is class component but you can make a functional component and use it.

import React from "react";
import { BrowserRouter as Router, Routes, Route } from "react-router-dom";
import HomePage from './pages/HomePage.jsx';
import NotFoundPage from './NotFoundPage.jsx';
import Footer from './Footer';
class App extends React.Component {
    render(){
        return(
            <Router>
                <Routes>
                    <Route exact path='/' element={HomePage} />
                    <Route path="*" element={NotFoundPage} />
                </Routes>
                 <Routes>
                     <Route path="/" element={Footer}/>
                 </Routes>
            </Router>
        )
    }
}
   
export default App;
Kannu Mandora
  • 479
  • 2
  • 10
-1
import {BrowserRouter as Router, Routes, Route, Navigate} from 'react-router-dom';

function App() {
  return (
    <>  
   <Router>
   <Routes>
   <Route exact path='/home' element={<Home/>}/>
    <Route exact path='/contact' element={<Contact/>}/>
    <Route exact path='/about' element={<About/>}/>
    <Route path="/404" element={<PageNotFound/>} />
    <Route path="*" element={<Navigate to="/404" />} />
   </Routes>
   </Router>
    </> 
  );
}
export default App;
General Grievance
  • 4,555
  • 31
  • 31
  • 45
  • As it’s currently written, your answer is unclear. Please [edit] to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Apr 21 '23 at 01:07