React Nested Routing

Savindu Pasintha
2 min readNov 16, 2022

Nested Routes are a powerful feature. While most people think React Router only routes a user from page to page, it also allows one to exchange specific fragments of the view based on the current route.

Code Bellow

index.js

import React from ‘react’

import ReactDOM from ‘react-dom’

import { BrowserRouter } from ‘react-router-dom’

import App from ‘./App’

import NewstedRouts from ‘./components/ReactNestedRoutingWithOutlet/NestedRouts’

ReactDOM.render(

<React.StrictMode>

<BrowserRouter>

<NewstedRouts />

</BrowserRouter>

</React.StrictMode>,

document.getElementById(‘root’),

)

NewstedRouts.js

import React from ‘react’

import { Routes, Route } from ‘react-router-dom’

import { Details } from ‘./Tabs/Datails’

import { Followers } from ‘./Tabs/Followers’

import { Following } from ‘./Tabs/Following’

import { Profile } from ‘./Tabs/Profile’

import { TabNav } from ‘./Tabs/TabNav’

function NewstedRouts() {

return (

<div className=”Main”>

<Routes>

<Route path=”/” element={<TabNav />} />

<Route path=”/profile” element={<TabNav />}>

<Route path=”/profile/details” element={<Details />} />

<Route path=”/profile/followers” element={<Followers />} />

<Route path=”/profile/following” element={<Following />} />

</Route>

</Routes>

</div>

)

}

export default NewstedRouts

TabNav.js

import React from ‘react’

import { Link, Outlet, useLocation } from ‘react-router-dom’

export function TabNav() {

const { pathname } = useLocation()

return (

<div>

<div className=”buttons”>

<Link

to=”/profile/details”

className={pathname === ‘/profile’ ? ‘activeBtn’ : ‘navBtn’}

>

Profile

</Link>

<Link

to=”/profile/followers”

className={pathname === ‘/profile/followers’ ? ‘activeBtn’ : ‘navBtn’}

>

Followers

</Link>

<Link

to=”/profile/following”

className={pathname === ‘/profile/following’ ? ‘activeBtn’ : ‘navBtn’}

>

Following

</Link>

</div>

<Outlet />

</div>

)

}

Tabs/Details.js

import React from ‘react’

import { Link } from “react-router-dom”;

export function Details() {

return (

<div className=”details”>

Name: Rajat Gupta

<br />

Followers: 5

<br />

Following: 7

<br />

Country: India

</div>

);

}

Tabs/Followers.js

import React from ‘react’

import { Link } from “react-router-dom”;

export function Followers() {

return (

<ul className=”details”>

<li>Aarav</li>

<li>Bhaarav</li>

<li>Sarav</li>

<li>Naarav</li>

<li>Paarav</li>

</ul>

);

}

Thank you !

Sign up to discover human stories that deepen your understanding of the world.

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

No responses yet

Write a response