Routing
- Install and set up React Router:
React Router is a popular library for handling routing in React applications. To get started:
a. Install React Router:
npm install react-router-dom
b. Set up the router in your main App component:
import React from "react";import { BrowserRouter as Router, Routes, Route } from "react-router-dom";import Home from "./components/Home";import About from "./components/About";import Contact from "./components/Contact";
function App() { return ( <Router> <Routes> <Route path="/" element={<Home />} /> <Route path="/about" element={<About />} /> <Route path="/contact" element={<Contact />} /> </Routes> </Router> );}
export default App;
This setup wraps your app in a Router
component and defines Routes
with individual Route
components for each page.
- Create multiple pages and navigate between them:
a. Create separate components for each page:
import React from 'react';
function Home() { return <h1>Welcome to the Home page</h1>;}
export default Home;
// About.jsimport React from 'react';
function About() { return <h1>About Us</h1>;}
export default About;
// Contact.jsimport React from 'react';
function Contact() { return <h1>Contact Us</h1>;}
export default Contact;
b. Use the Link
component to create navigation links:
import React from "react";import { Link } from "react-router-dom";
function Navigation() { return ( <nav> <ul> <li> <Link to="/">Home</Link> </li> <li> <Link to="/about">About</Link> </li> <li> <Link to="/contact">Contact</Link> </li> </ul> </nav> );}
export default Navigation;
c. Include the Navigation component in your App:
import React from "react";import { BrowserRouter as Router, Routes, Route } from "react-router-dom";import Home from "./components/Home";import About from "./components/About";import Contact from "./components/Contact";import Navigation from "./components/Navigation";
function App() { return ( <Router> <Navigation /> <Routes> <Route path="/" element={<Home />} /> <Route path="/about" element={<About />} /> <Route path="/contact" element={<Contact />} /> </Routes> </Router> );}
export default App;
Now you have a basic multi-page React application with navigation. Users can click on the links to navigate between pages, and the URL will update accordingly.
For programmatic navigation (e.g., after form submission), you can use the useNavigate
hook:
import { useNavigate } from 'react-router-dom';
function SomeComponent() { const navigate = useNavigate();
const handleSubmit = (event) => { event.preventDefault(); // ... handle form submission navigate('/thank-you'); // Navigate to a thank you page };
return ( // ... component JSX );}
This setup provides a foundation for creating a multi-page React application with client-side routing. You can expand on this by adding more pages, implementing nested routes, or using route parameters for dynamic content.