React Beginner 7: Routing with React Router

In this tutorial, you will learn how to create multi-page React applications using React Router, allowing users to navigate between different components without reloading the page.

Introduction

React applications are single-page by default, but you can create multiple “pages” using React Router. This library allows navigation and dynamic rendering of components based on the URL.

1. Install React Router

Use npm to install React Router:

npm install react-router-dom

2. Set Up Routes

Edit main.jsx to wrap your app with BrowserRouter:

import React from 'react';
import ReactDOM from 'react-dom/client';
import { BrowserRouter } from 'react-router-dom';
import App from './App.jsx';

ReactDOM.createRoot(document.getElementById('root')).render(
  <React.StrictMode>
    <BrowserRouter>
      <App />
    </BrowserRouter>
  </React.StrictMode>
);

3. Create Pages

Create two components representing pages: Home and About.

// Home.jsx
function Home() {
  return <h2>Welcome to the Home Page</h2>;
}
export default Home;

// About.jsx
function About() {
  return <h2>About This App</h2>;
}
export default About;

4. Configure Routes

Edit App.jsx to define routes and navigation:

import { Routes, Route, Link } from 'react-router-dom';
import Home from './Home.jsx';
import About from './About.jsx';

function App() {
  return (
    <div>
      <nav>
        <Link to="/">Home</Link> | 
        <Link to="/about">About</Link>
      </nav>

      <Routes>
        <Route path="/" element=<Home /> />
        <Route path="/about" element=<About /> />
      </Routes>
    </div>
  );
}

export default App;

5. Test Navigation

Run your app. Clicking the links should navigate between Home and About without reloading the page. React Router handles dynamic component rendering based on the URL.

6. Summary

In this tutorial, you learned:

  • How to install React Router
  • How to wrap your app with BrowserRouter
  • How to define pages as components
  • How to configure routes with Routes and Route
  • How to navigate between pages using Link

Next, in React Beginner 8, you will learn about the Context API and advanced hooks to manage global state across your app.

Previous Article

React Beginner 6: Fetching Data from an API

Next Article

React Beginner 8: Context API & Hooks

Write a Comment

Leave a Comment

Your email address will not be published. Required fields are marked *

Subscribe to our Newsletter

Subscribe to our email newsletter to get the latest posts delivered right to your email.
Pure inspiration, zero spam ✨