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.

Note

Make widgets available to the SDK using the setWidget or setWidgetType functions.

To add widget components based on page URL:

  1. In your React project, open your Application component then paste the following code block:

    import 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>
      );
    };
    Note

    header_ps and footer_rec are configured to appear on all pages in the CEC.

  2. Replace widget UI components with your UI components and configure them as widget components with the setWidget function.

  3. To clear errors if displayed, replace with your widgets and fix import statements.

  4. To test integration, visit various pages and verify that they render widgets according to the CEC.

If you have suggestions for improving this article, let us know!