SoFunction
Updated on 2025-04-07

React implements routing interception sample code

Let me briefly introduce the project background. I made a demo here. The front-end uses mock data, and then implements simple routing interception to verify whether the session contains the user as the basis for logging in. react-router-dom is v6. Unlike vue that we can set login intercept beforeenter, we need to add react ourselves.

//
import React, { lazy } from "react";
import { Navigate } from 'react-router-dom'
 
const Error = lazy(() => import("@/pages/Error/"))
const Index = lazy(() => import("@/pages/Index/"))
const Login = lazy(() => import("@/pages/Login/"))
 
export const routes = [
    {
        path: "/",
        element: <Navigate to="/index"/>
    },
    {
        path: "/login",
        element: <Login />
    },
    {
        path: "/index",
        element: <Index />
    },
    {
        path: "*",
        element: <Error />
    },
]
import React, { useEffect, Suspense } from 'react'
import { useRoutes, useNavigate } from 'react-router-dom'
import { routes } from './router'
 
export default function Index() {
    const element = useRoutes(routes)
 
    return (
        &lt;Authen route={element} children={}&gt;
            &lt;Suspense&gt;
                &lt;div&gt;{element}&lt;/div&gt;
            &lt;/Suspense&gt;
        &lt;/Authen&gt;
    )
 
}
//Implement routing interceptionconst Authen = (props) =&gt; {
    const navigate = useNavigate()
    const { route, children } = props
    const username = ('username')
    (props);
    useEffect(() =&gt; {
        if ( === "/login" &amp;&amp; username) {
            navigate('/index')
        }
    }, [route, navigate,username])
    return children
}
 

The Surpense component is when the react component is lazy to load, and the route jumps. Due to network reasons, the component content cannot pass in time, and an error will be reported if it is not added.

This is the article about the sample code for react to implement routing interception. For more related react routing interception content, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!