10

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

and make a component receive the id to handle it

1 Answer 1

12

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.

3
  • 2
    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. Commented Sep 3, 2018 at 19:30
  • Hi AmrElsehemy , were you able to solve this in Integrated Mode? I have the same problem and I haven't resolve it yet. Can you give me an information if you were able solved this. Thanks.
    – Jovit Mayo
    Commented Jul 3, 2019 at 13:29
  • @JovitMayo yes, it's been a while are you still stuck? you basically add an item resolver and resolve those urls to your base item Commented Jul 26, 2019 at 9:49

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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