Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading