How to create customRouteWrapper for Route in React Router v6?

Viewed 1334

I need to have a customWrapper for my Route in react-router v6 because I need to pass different props and layouts. before that in v5 I didn't have issue in create a custom function that returns a Route and I use that function inside Routes but in v6 I got this error:

Error: [RouteWrapper] is not a <Route> component. All component children of <Routes> must be a <Route> or <React.Fragment>

I tried to use fragments inside Routes but no luck same error shows up. here's my implementation:

return (
        <Layout {...layoutProps} onAnimationEnd={onAnimationEnd} isInTransitionStage={isInTransitionStage}>
            <Routes location={displayLocation}>
                <React.Fragment>
                    <RouteWrapper
                        path='/'
                        // component={HomePage}
                        layout={MainLayout}
                        setLayout={setLayout}
                        setLayoutProps={setLayoutProps}
                    />
                </React.Fragment>
            </Routes>
        </Layout>
    );
};

const RouteWrapper = ({path, component, layout}) => {
    return <Route path={path} element={layout} />;
};

1 Answers

The doc for version 6 says If you'd prefer to define your routes as regular JavaScript objects instead of using JSX, try useRoutes instead.

import * as React from "react";
import { useRoutes } from "react-router-dom";

function App() {
  let element = useRoutes([
    {
      path: "/",
      element: <Home />,
      // children: [/* nested routes */]
    },
    { path: "your-path", element: <RouteWrapper /> }
  ]);

  return element;
}
Related