Chandan Nick
Chandan Nick

Reputation: 31

How to convert this Route to new react router style

In my project, I saw router v5.2.0 is installed and based on that, routes are defined on where all route are under the switch. I am working on update of react-router to latest version, so first I am converting all route with CompactRoute

Here is My Current Route:

<Route
  path={
    '/' +
    Constants.USER_ADMIN_TYPE +
    '/show-details/:name/:showId'
  }
  render={(props) => (
    <Admin
      userType={Constants.USER_ADMIN_TYPE}
      comp={
        <ShowDetails
          {...props}
          userType={
            Constants.USER_ADMIN_TYPE
          }
        />
      }
    />
  )}
/>

I need help to convert this to latest react-router syntax.

I had tried, doing like this but its not rendering, and also I am confused, how can I pass the props in new router?

<CompatRoute
  path={
    '/' +
    Constants.USER_ADMIN_TYPE +
    '/show-details/:name/:showId'
  }
  component={
    <Admin
      userType={Constants.USER_ADMIN_TYPE}
      comp={
        <ShowDetails
          userType={
            Constants.USER_ADMIN_TYPE
          }
        />
      }
    />
  }
/>

Upvotes: 1

Views: 699

Answers (1)

Drew Reese
Drew Reese

Reputation: 202686

Given your react-router-dom@5 route:

<Route
  path={'/' + Constants.USER_ADMIN_TYPE + '/show-details/:name/:showId'}
  render={(props) => (
    <Admin
      userType={Constants.USER_ADMIN_TYPE}
      comp={
        <ShowDetails
          {...props}
          userType={
            Constants.USER_ADMIN_TYPE
          }
        />
      }
    />
  )}
/>

To convert this to the react-router-dom@6 APIs/syntax ensure the following:

  1. Render all Route components within a Routes component. The Routes component is the spiritual successor to, and replacement of, the RRDv5 Switch component. The Routes component is what does the heavy lifting of matching the current URL path to a route it manages.
  2. Render all routed content on the Route component's single element prop as a React.ReactNode, a.k.a. as JSX.
  3. There are no longer "route props", i.e. the RRDv5 history, location, and match route props. These are all now accessed via React hooks: location via useLocation, params via useParams, and instead of a history object there is now a navigate function via the useNavigate hook.

The above route converted to RRDv6 route API/syntax:

<Routes>
  ... other routes ...
  <Route
    path={`/${Constants.USER_ADMIN_TYPE}/show-details/:name/:showId`}
    element={(
      <Admin
        userType={Constants.USER_ADMIN_TYPE}
        comp={<ShowDetails userType={Constants.USER_ADMIN_TYPE} />}
      />
    )}
  />
  ... other routes ...
</Routes>

Upvotes: 1

Related Questions