Skip to content

Setup Client Based Routing

Tyler Ruff edited this page Jun 20, 2022 · 1 revision
  1. First, install React Router v6
npm install react-router-dom@6
  1. Then, open src/index.js, and insert the following:
    import * as React from "react";
    import ReactDOM from "react-dom/client";
    import { BrowserRouter } from "react-router-dom";
    import "./index.css";
    import App from "./App";
    import reportWebVitals from "./reportWebVitals";

    const root = ReactDOM.createRoot(
    document.getElementById("root")
    );
    root.render(
    <React.StrictMode>
        <BrowserRouter>
        <App />
        </BrowserRouter>
    </React.StrictMode>
    );
  1. Open src/App.js and add the following:
    import * as React from "react";
    import { Routes, Route, Link } from "react-router-dom";
    import "./App.css";

    function App() {
        return (
            <div className="App">
                <h1>Welcome to React Router!</h1>
                <Routes>
                    <Route path="/" element={<Home />} />
                    <Route path="about" element={<About />} />
                </Routes>
            </div>
        );
    }
  1. Further down in src/App.js, create your route pages:
    // App.js
    function Home() {
        return (
            <>
                <main>
                    <h2>Welcome to the homepage!</h2>
                    <p>You can do this, I believe in you.</p>
                </main>
                <nav>
                    <Link to="/about">About</Link>
                </nav>
            </>
        );
    }

    function About() {
        return (
            <>
                <main>
                    <h2>Who are we?</h2>
                    <p>
                        That feels like an existential question, don't you
                        think?
                    </p>
                </main>
                <nav>
                    <Link to="/">Home</Link>
                </nav>
            </>
        );
    }

Sources

Clone this wiki locally