How to remove trailing slash from URL with react router version 6?

import React from 'react';
import { Routes, Route, Navigate } from "react-router-dom";
import Home from './components/Home';
import About from './components/About';
import NotFound from './components/NotFound';

function App() {
  return (
    <div className="App">
      <h1>Welcome to React Router!</h1>
      <Routes>
        <Route path="/" element={<Home />} />
        <Route path="/about" element={<About />} />
        <Route path="/404" element={<NotFound />} />
        <Route path="*" element={<Navigate to="/404" />} />
      </Routes>
    </div>
  )
}

export default App

I want my url like this: https://example.com/about
Not: https://example.com/about/

I want to completely remove / from the end.
User can still see same page from https://example.com/about/

I want to redirect from this https://example.com/about/ to https://example.com/about
Without Trailing Slash.

>Solution :

this should work

React Router v6 solution

RemoveTrailingSlash.tsx

import React from "react";
import {Navigate, useLocation} from "react-router-dom";

export const RemoveTrailingSlash = ({...rest}) => {
    const location = useLocation()

    // If the last character of the url is '/'
    if (location.pathname.match('/.*/$')) {
        return <Navigate replace {...rest} to={{
            pathname: location.pathname.replace(/\/+$/, ""),
            search: location.search
        }}/>
    } else return null
}

App.tsx

import React from 'react';
import { Routes, Route, Navigate } from "react-router-dom";
import Home from './components/Home';
import About from './components/About';
import NotFound from './components/NotFound';
import RemoveTrailingSlash from './RemoveTrailingSlash.tsx'

const App=()=> {
  return (
    <div className="App">
      <h1>Welcome to React Router!</h1>
<RemoveTrailingSlash/>
      <Routes>
        <Route path="/" element={<Home />} />
        <Route path="/about" element={<About />} />
        <Route path="/404" element={<NotFound />} />
        <Route path="*" element={<Navigate to="/404" />} />
      </Routes>
    </div>
  )
}

export default App

Leave a Reply