Step 1: Setup React Router v6
npm i -D react-router-dom@latest
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;
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!
Top comments (0)