Building a Layout with React Router v6: Step-by-Step Guide

Ravi Patel
2 min readMar 6, 2024

--

In this step-by-step guide, we’ll walk through the process of building a layout using React Router v6. We’ll create a simple application with multiple routes and a shared layout component.

Step 1: Setup React Router v6

First, let’s set up a new React application and install React Router v6:

npx create-react-app router-app
cd router-app
npm install react-router-dom@next

Step 2: Define Route Structure

Next, define the structure of your routes in the App.js file. We'll create routes for the home, about, and contact pages, and associate them with corresponding components.

// App.js
import React from 'react';
import { BrowserRouter as Router, Routes, Route } from 'react-router-dom';
import Layout from './Layout';
import Home from './Home';
import About from './About';
import Contact from './Contact';

function App() {
return (
<Router>
<Routes>
<Route path="/" element={<Layout />}>
<Route index element={<Home />} />
<Route path="/about" element={<About />} />
<Route path="/contact" element={<Contact />} />
</Route>
</Routes>
</Router>
);
}

export default App;

Step 3: Create Layout Component

Now, let’s create a layout component (Layout.js) that will contain our shared header and main content area.

// Layout.js
import React from 'react';
import { Outlet } from 'react-router-dom';

function Layout() {
return (
<div>
<header>
<h1>My App</h1>
<nav>
<ul>
<li><a href="/">Home</a></li>
<li><a href="/about">About</a></li>
<li><a href="/contact">Contact</a></li>
</ul>
</nav>
</header>
<main>
<Outlet />
</main>
</div>
);
}

export default Layout;

Step 4: Create Page Components

Create separate components for the home, about, and contact pages. These components will represent the content of each page.

Home Component

// Home.js
import React from 'react';

function Home() {
return (
<div>
<h2>Home Page</h2>
<p>Welcome to the home page!</p>
</div>
);
}

export default Home;

About Component

// About.js
import React from 'react';

function About() {
return (
<div>
<h2>About Page</h2>
<p>Learn more about us!</p>
</div>
);
}

export default About;

Contact Component

// Contact.js
import React from 'react';

function Contact() {
return (
<div>
<h2>Contact Page</h2>
<p>Reach out to us!</p>
</div>
);
}

export default Contact;

Step 5: Test Your Application

Start your application and test it in the browser:

npm start

Navigate to different routes (e.g., /about, /contact) to see the layout and content changing accordingly.

Conclusion

Congratulations! You’ve successfully built a layout using React Router v6, allowing you to navigate between different pages while maintaining a consistent layout across the application. This approach provides a clean and organized structure for your React applications with multiple routes. Experiment with adding more routes and components to further enhance your application!

--

--