What are nested routes in React?

Nested routes are one of React’s unique features that allow users to swap out specific view fragments based on the current path.

Multiple tabs (profile and account in this case) can be displayed on a single user page to facilitate browsing through a user’s information. When one of these tabs gets clicked, the URL in the browser and the content of the tab change, but the layout stays the same.

Nested account and profile page

Code example

Here is a coding example that demonstrates the usage of nested routing in a React application. The App component sets up Router from the react-router-dom library and defines two main routes: Home and User. The User route further contains two nested routes: Profile and Account. The Link components are used for navigation. This setup allows for rendering different components based on the current route, creating a multi-level navigation structure in the application.

import React from 'react';
import './App.css';
import {BrowserRouter as Router, Link, Routes, Route} from 'react-router-dom'
import Account from './Components/Account';
import Profile from './Components/Profile';
import User from './Pages/User';
import Home from './Pages/Home';

function App() {
  return (
    <div className="App">
      <Router>
      
        <nav>
        
          <Link to="/">Home  </Link>
       

          <Link to="user">User</Link>
         
        </nav>
       
        <Routes>
          <Route path="/" element={<Home/>} />
          <Route path="/user" element={<User/>}>
            <Route path="profile" element={<Profile/>} />
            <Route path="account" element={<Account/>}/>
          </Route>
        </Routes>
     </Router>
    </div>
  );
}
  
export default App;


React Router navigation with nested routes

Note: Click on the "Run" button and open the URL provided after "Your app can be found at".

Code explanation

Line 25–28: The user page uses nested routing to render the selected component (profile or account).

Conclusion

A nested route is a section of a website layout that responds to changes in the route. When moving from one URL to another in a single-page application, there is no need to render the full page; only the parts of the page that are dependent on that URL change.

Free Resources

Copyright ©2024 Educative, Inc. All rights reserved