Search code examples
javascriptreactjsreact-routerreact-router-dom

Difference between declaring Routes in React Router v6 and v6.4+


I've tried searching that, however, couldn't really find whether using React Fragments is okay to achieve the same behavior as pre-v6.4?

const Routes6 = (
  <Routes>
    <Route path="/" element={<Home />} />
    <Route path="posts" element={<Posts />}>
      <Route path="/posts/new" element={<NewPost />} />
    </Route>
  </Routes>
);
const routes64 = createBrowserRouter(
  createRoutesFromElements(
    <>
      <Route path="/" element={<Home />} />
      <Route path="/posts" element={<Posts />}>
        <Route path="/posts/new" element={<NewPost />} />
      </Route>
    </>,
  ),
);

Solution

  • I see no reason why using React.Fragements wouldn't work to implement the routes using the new RRDv6.4+ data router. A more conventional method that avoids the React.Fragment may be to use a root route on "/" and render the Home component on an index route.

    Example:

    const routes64 = createBrowserRouter(
      createRoutesFromElements(
        <Route path="/">
          <Route index element={<Home />} />
          <Route path="/posts" element={<Posts />}>
            <Route path="new" element={<NewPost />} />
          </Route>
        </Route>,
      ),
    );