John
John

Reputation: 8946

how to add slash in react router path

I have developed a page with react whose route is

http://example.come/page1

When the url is loaded I need to append a slash at the end of the url like this

http://example.come/page1/

My Routes are like this

  Router history={browserHistory}>
    <Route path='/' component={Home} />
    <Route path='/page1' component={Page1} />
</Router>

I tried to change the path directly to "/page1/" instead of "/page1" but this will not load http://example.com/page1 , It will open only http://example.com/page1/

I want both the path to load the Page1 component

Upvotes: 5

Views: 8229

Answers (4)

Michael Kim
Michael Kim

Reputation: 771

Came across this using React Router v6 (2023). This is my solution:

function EnforceTrailingSlash() {
  const { pathname } = useLocation();
  if (!pathname.endsWith('/')) {
    return <Navigate to={`${pathname}/`} />;
  }
  return <Outlet />;
}

const router = createBrowserRouter(
  createRoutesFromElements(
    <Route
      element={<EnforceTrailingSlash />}
    >
      ... Your nested routes here ...
    </Route>,
  ),
);

Upvotes: 1

soarinblue
soarinblue

Reputation: 1687

Better resolve the problem from web server, like Nginx, which rewrites the url to add the trailing slash at the end of url.

Upvotes: 0

Vikas
Vikas

Reputation: 531

Above answer will work fine and you will achieve what you need. But there is a catch. Open developers tool and click on network tab then refresh your page....you will see status 302 page redirect from WITHOUT trailing slash path to WITH trailing slash path.

And this is not very good. Atleast set status to 301.

How to set status ? https://github.com/ReactTraining/react-router/issues/458

Upvotes: 1

Andre Lee
Andre Lee

Reputation: 1320

According to this reply, https://github.com/ReactTraining/react-router/issues/820#issuecomment-256814655

Using hooks (onEnter and onChange) with react-router v2 or above may achieve what you need.

Upvotes: 2

Related Questions