React - Redirect to a default path if path doesn't exist

Viewed 3144

I was creating a simple react app. I just want to know how to redirect to a certain path if the inputted path doesn't exist.

import React, { useState, useEffect } from 'react';
import { BrowserRouter, Route, Routes, Navigate } from 'react-router-dom';
import HomePage from './screens/HomePage/home';

function App() {

  return (
    <BrowserRouter>
      <Routes>
        <Route path="/" element={<HomePage/>} />
      </Routes>
    </BrowserRouter>
  );
}

export { App };

Let say I went to "localhost:3000/login", but since the path doesn't exist I want it to automatically redirect to "localhost:3000" as the default.

4 Answers

you can add * to your path, so if the existing path does not match, then it hits this route, and you can redirect to wherever you want.

Here is the code snippet:

import React, { useState, useEffect } from 'react';
import { BrowserRouter, Route, Routes, Navigate } from 'react-router-dom';
import HomePage from './screens/HomePage/home';

function App() {

  return (
    <BrowserRouter>
      <Routes>
        <Route path="/" element={<HomePage/>} />
        <Route path="/some-existing" element={<SomeComponent />} />
        <Route path="*" element={<HomePage />} /> // page-not-found route
      </Routes>
    </BrowserRouter>
  );
}

export { App };

The best way would be to use Redirect component in the last Route of the list:

import React, { useState, useEffect } from 'react';
import { BrowserRouter, Route, Routes, Navigate, Redirect } from 'react-router-dom';
import HomePage from './screens/HomePage/home';

function App() {

  return (
    <BrowserRouter>
      <Routes>
        <Route path="/">
          <HomePage />
        </Route>
        <Route path="*">
          <Redirect to="/" />
        </Route>
      </Routes>
    </BrowserRouter>
  );
}

export { App };

I managed to do it by doing this:

I created a MissingRoute.js

import React from 'react';
import { Navigate } from 'react-router-dom';

function MissingRoute() {
 return < Navigate to={{pathname: '/'}} / >
}

export { MissingRoute }

Then use it as an element in the routes:

<Routes>
 <Route path="*" element={<MissingRoute/>} />
</Routes>

For older versions of react, you might need to do it differently and use "Redirect" instead of "Navigate"

It might be convoluted. Let me know if there is a cleaner way to do this. But this is what I got for now.

In react-router v6, you could do something like this:

<BrowserRouter>
  <Routes>
    <Route path="/" element={<HomePage/>} />
    <Route path="*" element={<Navigate to='/' replace />} />
  </Routes>
</BrowserRouter>
Related