How to add a route like app/payments/:id in JSS
and make a component receive the id to handle it
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.