How to add a route like app/payments/:id in JSS

and make a component receive the id to handle it

up vote 8 down vote accepted

Assuming you wish to use Sitecore layout data for the custom route:

Teach the app about the route. In RouteHandler.js:

<Switch>
  // add this
  <Route key="myCustomRoute" path="/app/payments/:id" render={customRouteRenderFunction} />

  {routePatterns.map((routePattern) => (
    <Route key={routePattern} path={routePattern} render={routeRenderFunction} />
  ))}
</Switch>

Then implement the render function that will process your custom route and inject the :sitecoreRoute param that the RouteHandler needs to fetch the Sitecore data. This param will affect which Sitecore item provides the layout for the custom route. For example:

const customRouteRenderFunction = (props) => {
  const handlerProps = { ...props };
  // this will make it use the styleguide route item for its layout data
  handlerProps.match.params.sitecoreRoute = '/styleguide';

  return <RouteHandler route={handlerProps} />;
};

Then you can use the withRouter() function from react-router to get the current route params within your components, and thus receive the :id param:

import { withRouter } from 'react-router-dom';

const MyComponent = (props) => <h1>my ID is: {props.match.params.id}</h1>

export default withRouter(MyComponent);

Note: custom routing like this will require customizing how Sitecore parses routes in C# to operate correctly in Integrated Mode. In integrated mode Sitecore is responsible for resolving routes, as opposed to the client side router. In most cases, using the route path without parameters mapped to a Sitecore item will be the simplest technique. Wildcard items in Sitecore are another useful technique to get client and server-side routing aligned.

If you do not wish to use Sitecore layout data within your route, then it can be mapped using standard react-router techniques.

  • Thanks for the details, actually that's exactly how I applied it. Works well in discounted mode, but when deploying to Sitecore the path wasn't found. I am missing the C# counterpart you mentioned in the note, can you give pointers to that part. – Amr Elsehemy Sep 3 at 19:30

Your Answer

By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Not the answer you're looking for? Browse other questions tagged or ask your own question.