Published:

React Router - Remove Trailing Slash from URLs

Tutorial built with React 16.13 and React Router 5.1.2

This is a super quick example of how to remove trailing slashes from URLs in React apps that use React Router.

The solution is to add the following react router <Redirect ... /> that matches any URL with a trailing slash and automatically redirects it to the same URL without the trailing slash.

<Redirect from="/:url*(/+)" to={pathname.slice(0, -1)} />


Here it is in action:(See on StackBlitz at https://stackblitz.com/edit/react-router-remove-trailing-slash)


React Router example app component that removes trailing slash

This is the complete code from the above example React App component that contains all of the react routes including the <Redirect .../> that removes trailing slashes. It gets the current pathname with the useLocation() hook provided by the React Router library.

Note: you can't call the useLocation() react hook in the same component that adds the <BrowserRouter> to the DOM, which is why I moved the <BrowserRouter> up one level in the example into /index.js.

import React from 'react';
import { Route, Switch, Redirect, Link, useLocation } from 'react-router-dom';

import { Home } from '../home';
import { TestPage } from '../test-page';

function App() {
    const { pathname } = useLocation();

    return (
        <div>
            <nav className="navbar navbar-expand navbar-dark bg-dark">
                <div className="navbar-nav">
                    <Link to="/" className="nav-item nav-link">Home</Link>
                    <Link to="/test-page/" className="nav-item nav-link">Test Page (link with trailing slash)</Link>
                </div>
            </nav>
            <Switch>
                <Redirect from="/:url*(/+)" to={pathname.slice(0, -1)} />
                <Route exact path="/" component={Home} />
                <Route path="/test-page" component={TestPage} />
            </Switch>
        </div>
    );
}

export { App };

 


Subscribe or Follow Me For Updates

Subscribe to my YouTube channel or follow me on Twitter, Facebook or GitHub to be notified when I post new content.

Other than coding...

I'm currently attempting to travel around Australia by motorcycle with my wife Tina on a pair of Royal Enfield Himalayans. You can follow our adventures on YouTube, Instagram and Facebook.


Need Some React Help?

Search fiverr to find help quickly from experienced React developers.



Supported by