Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to remove trailing slash in react-router URLs

I start to use react-router in my application and I am noting that when it has a trailing slash at end of URL (/url/) it does not work. I searched more about it, read all documentation and react-router issues and tried to use <Redirect from='/*/' to="/*" />, however it was not a good solution, cause it did not work too. So, reading more I found out a suggestion to insert /?at end of URL, but it still not worked.

The code of routes.js:

export default (
    <Route path="/" component={App}>
        <IndexRoute component={ProfileFillComponents} />
        <Route path="/seguro-residencia" handler={require('./components/Forms/Residencial/ProfileFill/profileFillComponents')} />
        <Route path="/seguro-residencia/informacoes-pessoais" component={CotationNumber} />
    </Route>
)

The code of index.js:

render((<Router history={browserHistory} routes={routes} />), document.getElementById('root'));

Searching more, I found a guy who made a function to force trailing slash at URLs and I resolved to make the opposite of that, forcing to not have it.

Update routes.js code with function No trailing slash function:

export default (
    <Route onEnter={forceTrailingSlash} onChange={forceTrailingSlashOnChange}>
        <Route path="/" component={App}>
            <IndexRoute component={ProfileFillComponents} />
            <Route path="/seguro-residencia" handler={require('./components/Forms/Residencial/ProfileFill/profileFillComponents')} />
            <Route path="/seguro-residencia/informacoes-pessoais" component={CotationNumber} />
        </Route>
    </Route>
)

function forceNoTrailingSlash(nextState, replace) {
  const path = nextState.location.pathname;
  if (path.slice(-1) === '/') {
    replace({
      ...nextState.location,
      pathname: path.slice(1,path.lastIndexOf('/')-1)
    });
  }
}    

function forceNoTrailingSlashOnChange(prevState, nextState, replace) {
  forceNoTrailingSlash(nextState, replace);
}

And again this did not work! I need to make this URLs more friendly as possible and I would like that URLs do not have any trailing slash at the end. Any suggestion how can I make this? And why Redirect did not work in this case?

like image 332
Aipi Avatar asked Jan 31 '17 01:01

Aipi


People also ask

What is a trailing slash in URL?

Email Subscription. A trailing slash is a forward slash (“/”) placed at the end of a URL such as domain.com/ or domain.com/page/. The trailing slash is generally used to distinguish a directory which has the trailing slash from a file that does not have the trailing slash.

How do you remove the last slash from a string?

Use the String. replace() method to remove a trailing slash from a string, e.g. str. replace(/\/+$/, '') . The replace method will remove the trailing slash from the string by replacing it with an empty string.

What is the BrowserRouter /> component?

BrowserRouter: BrowserRouter is a router implementation that uses the HTML5 history API(pushState, replaceState and the popstate event) to keep your UI in sync with the URL. It is the parent component that is used to store all of the other components.


Video Answer


1 Answers

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
}

AppRoutes.tsx

const AppRoutes: React.FC = () => {
    return (
        <React.Fragment>
            <RemoveTrailingSlash/>
            <Routes>
            {/* All your routes go here */}
            </Routes>
        </React.Fragment>
    )
}
like image 53
mleister Avatar answered Oct 15 '22 20:10

mleister