163

I am trying to upgrade to React Router v6 (react-router-dom 6.0.1).

Here is my updated code:

import { BrowserRouter, Navigate, Route, Routes } from 'react-router-dom';

<BrowserRouter>
  <Routes>
    <Route path="/" element={<Home />} />
    <Route path="/lab" element={<Lab />} />
    <Route render={() => <Navigate to="/" />} />
  </Routes>
</BrowserRouter>

The last Route is redirecting the rest of paths to /.

However, I got an error

TS2322: Type '{ render: () => Element; }' is not assignable to type 'IntrinsicAttributes & (PathRouteProps | LayoutRouteProps | IndexRouteProps)'.   Property 'render' does not exist on type 'IntrinsicAttributes & (PathRouteProps | LayoutRouteProps | IndexRouteProps)'.

However, based on the documentation, it does have render for Route. How can I use it correctly?

4

9 Answers 9

311

I think you should use the no match route approach.

Check this in the documentation: Adding a "No Match" Route

import { BrowserRouter, Navigate, Route, Routes } from 'react-router-dom';

<BrowserRouter>
  <Routes>
    <Route path="/" element={<Home />} />
    <Route path="/lab" element={<Lab />} />
    <Route
        path="*"
        element={<Navigate to="/" replace />}
    />
  </Routes>
</BrowserRouter>

To keep the history clean, you should set replace prop. This will avoid extra redirects after the user click back.

6
  • If you want to redirect outside react components or without hooks, check out this answer.
    – totymedli
    Feb 10, 2022 at 6:56
  • 1
    What if / is a parent route to those others? How do you prevent / itself from being a route that can be navigated to? And instead redirect / to say /home when home is a child under /? Apr 24, 2022 at 8:52
  • Worth noting that this has no SSR support for static routing 👍🏻
    – Neil
    May 11, 2022 at 10:46
  • 1
    @KashifAli in that case, you should replace the Navigation componet with you custom Not Found screen. I don't think you will be able to have both using a wildcard path. But you can use a Nested approach to limit when the user should be redirected inside some path. Jun 16, 2022 at 18:00
  • 1
    Is there any api docs on Navigate and replace? It seems that i should have stopped with the docs, but somehow ended here.
    – ColdHands
    Sep 19, 2022 at 11:37
61

I found another way to do this:

import { useNavigate } from "react-router-dom";
let navigate = useNavigate();

useEffect(() => {
   if (LoggedIn){
      return navigate("/");
   }
},[LoggedIn]);

See Overview, Navigation.

1
  • 3
    It says useNavigator can be used only in the context of the router. It can't be used alone. Oct 16, 2022 at 14:32
12

Create the file RequireAuth.tsx

import { useLocation, Navigate } from "react-router-dom";
import { useAuth } from "../hooks/Auth";

export function RequireAuth({ children }: { children: JSX.Element }) {
  let { user } = useAuth();
  let location = useLocation();

  if (!user) {
    return <Navigate to="/" state={{ from: location }} replace />;
  } else {
    return children;
  }
}

Import the component to need user a private router:

import { Routes as Switch, Route } from "react-router-dom";

import { RequireAuth } from "./RequireAuth";
import { SignIn } from "../pages/SignIn";
import { Dashboard } from "../pages/Dashboard";

export function Routes() {
  return (
    <Switch>
      <Route path="/" element={<SignIn />} />
      <Route
        path="/dashboard"
        element={
          <RequireAuth>
            <Dashboard />
          </RequireAuth>
        }
      />
    </Switch>
  );
}

0
8

In version 5 of React, i.e., react-router-dom, we had the Redirect component. But in version 6 of React it is updated to the Navigate components.

We can pass replace in these components to avoid unnecessary redirects on clicking back and forward option.

Demonstration for usage is attached below:

<Route  path="/" element={user ? <Home /> : <Register />} />
<Route path="/login" element={user ? <Navigate to="/" replace /> :  <Login />}  />
<Route path = "/register" element={user ? <Navigate to="/" replace /> :  <Register />} />
7

FOR react-router VERSION 6

New example after editing----->(more simple easy to read)

import {BrowserRouter as Router,Routes,Route} from 'react-router-dom';
import Home from '../NavbarCompo/About';
import Contact from '../NavbarCompo/Contact';
import About from '../NavbarCompo/About';
import Login  from '../NavbarCompo/Login';
import Navbar from '../Navbar/Navbar';
import Error from '../pages/error';
import Products  from '../pages/products';
import Data from '../NavbarCompo/Data';

const Roter=()=>{
    return (
    <Router>

            <Navbar />
        <Routes>
            
            <Route path='/' element={<Home />} />
            <Route path='/about' element={<About />} />
            <Route path='/contact' element={<Contact />} />
            <Route path='/login' element={<Login />} />
            <Route path='/product/:id' element={<Products />} />
            <Route path='/data' element={<Data />} />
            <Route path ='*' element={<Error />} />
        </Routes>


    </Router>
    )
}
export default Roter;

Look at the example

import React from "react";
import Form from "./compo/form";
import ReactDOM from "react-dom/client";
import { createBrowserRouter, RouterProvider, Route,Routes,Navigate } from "react-router-dom";

const router = createBrowserRouter([
  {
    path: "/",
    element: <Form />
  },
  {
    path: "/about",
    element: <h1>hola amigo,you are in about section</h1>
  },
  {
    path:"*",
    element:<Navigate to="/" replace />
  }
]);

const root = ReactDOM.createRoot(document.getElementById("root"));

root.render(
  <React.StrictMode>
    <RouterProvider router={router}></RouterProvider>
  </React.StrictMode>
);

check this out https://reactrouter.com/en/main/start/overview

1
5
      <BrowserRouter>
        <Routes>
          <Route path="home" element={<Home />} />
          <Route path="about" element={<About />} />
          <Route index element={<Navigate to="/home" replace />} />
        </Routes>
      </BrowserRouter>
3
import { useNavigate } from "react-router-dom";
import { Button } from "@mui/material";

const component =()=>{

    const navigate = useNavigate();

    const handelGoToLogin = () => {
        navigate('/auth/login')
    }

    return(<>
        //.........
    
        <Button onClick={handelGoToLogin} variant="outlined" color="primary" size="large" fullWidth>
             Back
        </Button>

    </>)
}
2
import { useState } from "react"
import { Navigate } from "react-router-dom"
const [login, setLogin] = useState(true)
return (<>
{!login && <Navigate to="/login" />}
<>)
0

For class components, at the first you should make a functional component, and then use HOC technical to use useNavigate React hook.

Like this:

File withrouter.js

import {useNavigate} from 'react-router-dom';

export const withRouter = WrappedComponent => props => {
    return (<WrappedComponent {...props} navigate={useNavigate()}/>);
};

Then use it in other class components like this:

export default withRouter(Signin);

And use props for redirect like this:

this.props.navigate('/');

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.