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

Time:11-15

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.

CodePudding user response:

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 };

CodePudding user response:

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 };
  • Related