Basic ReactJS Routing

ReactJS Routing including route params

Posted on February 4, 2022

We’ll assume you already have a basic ReactJS app. If not, you can create one using create-react-app. The NPM module can be found here.

1: Add BrowserRouter to index.js

import React from 'react';
import ReactDOM from 'react-dom';
import {BrowserRouter} from "react-router-dom";
import './index.css';
import App from './App';

ReactDOM.render(
    <BrowserRouter\>
        <App/>
    </BrowserRouter>,
    document.getElementById("root")
);

2: Import your components and add your routes to App.js. In this case we have 2 components, one for a contact page and one for a single page.

Note we’ve also added a route with a route parameter of :id

import React from 'react';
import {Routes, Route} from "react-router-dom";
import './App.css';
import Contact from './components/contact/contact.js';
import Home from './components/home/home.js';
import Single from "./components/single/single";
function App() {
    return (
        <React.Fragment>
            <Routes>
                <Route path="/" element={<Home/>}/>
                <Route path="contact" element={<Contact/>}/>
                <Route path="single/:id" element={<Single/>}/>
            </Routes>
        </React.Fragment>
    );
}
export default App;

3: Add some navigation links to your App.js component

You should add these links to a separate header component so you can include it in all of your components/routes. I’ve just added it here for the sake of brevity.

import React from 'react';
import {Routes, Route} from "react-router-dom";
import './App.css';
import Contact from './components/contact/contact.js';
import Home from './components/home/home.js';
import Single from "./components/single/single";
function App() {
    return (
        <React.Fragment>
            <nav>
                <Link to="/">Home</Link>
                <Link to="/contact">Contact</Link>
                <Link to="/single/19">Single Page</Link>
            </nav>
            <Routes>
                <Route path="/" element={<Home/>}/>
                <Route path="contact" element={<Contact/>}/>
                <Route path="single/:id" element={<Single/>}/>
            </Routes>
        </React.Fragment>
    );
}
export default App;

4: You can then get the :id route parameter on your page by using useParams

import React from 'react';
import './single.css';
import { useParams } from 'react-router-dom';

function Single() {

    const params = useParams();

    return (
        <React.Fragment>
            <h1>{params.id}</h1>
        </React.Fragment>
    );
}
export default Single;