React Router v6 - How to use @ symbol in route?

Viewed 232

I'm using react-router-dom to manage my routes:

<Routes>
    <Route path="/" element={<MainLayout />}>
        <Route index element={<Home />} />
        <Route path="@:profileId" element={<Profile />} />
    </Route>
<Routes>

I want to use @ prefix at profile route but error is no routes matched location "/@username"

How to fix it?

1 Answers

It seems there's a bug filed for this issue, and 1 or 2 open pull requests in the works. Fortunately (or unfortunately) these sorts of paths work fine in non-layout routes.

A workaround until the bug/issue is resolved:

Convert the MainLayout into a wrapper component and wrap the routed components individually. Basically consume a children prop and render children where the Outlet component was previously.

Example MainLayout layout component:

const MainLayout = () => (
  <>
    <h1>MainLayout</h1>
    <Outlet />
  </>
);

becomes

const MainLayout = ({ children }) => (
  <>
    <h1>MainLayout</h1>
    {children}
  </>
);

And the routes from

<Routes>
  <Route path="/" element={<MainLayout />}>
    <Route index element={<Home />} />
    <Route path="@:profileId" element={<Profile />} />
  </Route>
</Routes>

to

<Router>
  <Routes>
    <Route
      path="/"
      element={
        <MainLayout>
          <Home />
        </MainLayout>
      }
    />
    <Route
      path="/@:profileId"
      element={
        <MainLayout>
          <Profile />
        </MainLayout>
      }
    />
  </Routes>
</Router>

Edit react-router-v6-how-to-use-symbol-in-route

Related