Render widget UI components based on page URI
Pages are containers for widgets and have an associated URL or a URL pattern. A common solution involves rendering widgets based on URL.
The following procedure describes the most common way to use a router to add widget UI components based on page URI.
Make widgets available to the SDK using the setWidget or setWidgetType functions.
To add widget components based on page URL:
-
In your React project, open your
Applicationcomponent then paste the following code block:RequestResponseimport WidgetsProvider from "@sitecore-discover/react"; import createTheme from "@sitecore-discover/ui"; import CUSTOM_THEME from "./widget_components/customTheme"; import PreviewSearchWidget from "./widget_components/previewSearchWidget"; import RecommendationWidget from "./widget_components/recommendationWidget"; import SearchtCategoriesWidget from "./widget_components/searchCategoriesWidget"; import SearchProductsWidget from "./widget_components/searchProductsWidget"; import TrendingRecommendationWidget from "./widget_components/trendingRecommendationWidget"; import MayLikeRecommendationWidget from "./widget_components/mayRecommendationWidget"; const theme = createTheme(CUSTOM_THEME); setWidget('cat_search', { type: WidgetDataType.SEARCH_RESULTS, component: SearchtCategoriesWidget} ); setWidget('prod_search', { type: WidgetDataType.SEARCH_RESULTS, component: SearchProductsWidget} ); setWidget('trend_rec', { type: WidgetDataType.RECOMMENDATION, component: TrendingRecommendationWidget} ); setWidget('may_like_rec', { type: WidgetDataType.RECOMMENDATION, component: MayLikeRecommendationWidget } ); const MyApp = () => { return ( <div style={theme.style}> <WidgetsProvider env="<environment>" customerKey="<customer key>" apiKey="<api key>" useToken > <header> <h1>My App</h1> <PreviewSearchWidget rfkId="header_ps" /> </header> <div class="content"> <PageWidgets /> </div> <footer> <RecommendationWidget rfkId="footer_re" /> </footer> </WidgetsProvider> </div> ); };Noteheader_psandfooter_recare configured to appear on all pages in the CEC. -
Replace widget UI components with your UI components and configure them as widget components with the
setWidgetfunction. -
To clear errors if displayed, replace with your widgets and fix import statements.
-
To test integration, visit various pages and verify that they render widgets according to the CEC.