reactjsurlroutes

In react how to build urls as "http://localhost:3000/app?path=user.home"


how do I provide ?path=some_path and every time I just want to change the some_path to access home,about,details etc and what is effective and reliable way to get this functionality in React?

I'm a bit familiar with Routers, but the functionality is little new to me

Also I'm using the React-router-dom v6


Solution

  • App.js

    import './App.css';
    import { BrowserRouter, Route, Routes } from 'react-router-dom';
    import { PageLayout } from './PageLayout';
    
    function App() {
        return (
            <BrowserRouter>
                <Routes>
                    <Route path="/" element={<div>Root</div>}/>
                    <Route path="/app" element={<PageLayout/>}/>
                </Routes>
            </BrowserRouter>
        );
    }
    
    export default App;
    

    PageLayout.js

    import React from 'react';
    import Home from './Home';
    import About from './About';
    
    export const PageLayout = () => {
        const query = new URLSearchParams(window.location.search)
        const url = query.get('path')
    
        const RenderOutlet = () => {
            if (!url) {
                return <Home />;
            }
            switch (url) {
                case 'home': return <Home/>;
                case 'about': return <About/>;
                default: return <div>404! Page Not Found!</div>;
            }
        }
    
        return (
            <div>
                <RenderOutlet/>
            </div>
        );
    };
    

    Note: Search parameters is not good practice of routing for base routes. It should be used for parametric routings like search, filter, tokens, etc.