How to use dynamic routing in NodeJs and ReactJs

How to use dynamic routing in NodeJs and ReactJs

An implementation of dynamic routing

ยท

2 min read

What is Dynamic URL Routing ?

Dynamic URL routing is a key element of several websites. As you can see on the image below, Instagram uses dynamic routing to display each user that has registered on their website.

insta_new.png

This means that individual routes are not created on the server for every single user manually. Instead, they manage their user account related routes through just one dynamic url.

Implementing Dynamic URL Routing in NodeJs

With an express server, dynamic routing is extremely easy to achieve. Let us try to imitate the dynamic routing used on instagram:

app.get("/user/:username", (req, res) => {
    res.send(`<h1>Hello ${req.params.username}</h1>`);
})

The static route in the above code is the 'user' part of the URL. The child route that follows is dynamic. We can symbolize a dynamic route with the ':' symbol in node js. The username of this dynamic route can now be accessed as well, using req.params.

Using this technique, we do not need to create individual routes for every single username that we identify.

Implementing Dynamic URL Routing in ReactJS

If you are working with a frontend framework, then the routes of this framework must be dynamic as well. Here is how to implement dynamic routing with version 6 React router.

First we must allow for all routes on the index.js file in our react project. So this is the setup for index.js:

import { BrowserRouter as Router, Routes, Route } from "react-router-dom";
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
    <Router>
        <Routes>
            <Route path="/*" element={<App />} />
        </Routes>
    </Router>
);

Now, we can manage our routes on the App.js file like so:

function App() {
    return (
        <>
        <Routes>
            <Route path="/user/:username" element={<User />}></Route>
        </Routes>
        </>
    );
}

In the above piece of code, we have imported the User component. To access the username attached as a dynamic route, we must use the React module 'useParams' in our component:

import { useParams } from "react-router-dom";

function User(){
    const params = useParams();
    return (
        <h1>Hello {params.username}</h1>
    )
}

That is it from this blog! Thank you for reading and I wish you happy coding!

ย