Render widgets by wrapping them in the PageWidgetsProvider component
The PageWidgetsProvider component wraps components that render widget components.
The following procedure shows how you can create a custom component to render widget components based on page URL. The query hook used for the URL is the usePageWidgets function.
To render widgets by wrapping them in the PageWidgetsProvider component:
-
In a folder called
widget_components, create a file calledcustomPageWidgets.js, paste the following code block, and customize for your widget components.NoteTo render widgets with the following
CustomPageWidgetscomponent:-
Pass your UI components through the
widget,setWidget, orsetWidgetTypefunctions before providing them toCustomPageWidgets.
RequestResponseimport { usePageWidgets, Widget } from "@sitecore-discover/react"; import MyRecommendationWidget from './widget_components/recommendation/widget'; const Loader = () => { return <div className="loader"> Loading... </div> } const CustomPageWidgetsComponent = () => { const { isLoading, data: widgets = [] } = usePageWidgets(); return ( <> {isLoading && <Loader />} {!isLoading && widgets.map((rfkId) => { if (rfkId === 'rfkid_1') { return <MyRecommendationWidget rfkId={rfkId} /> } return <Widget rfkId={rfkId} />; }) } </>); }; export default CustomPageWidgetsComponent; -
-
In your React application, in the application component, to initialize and authenticate the JS SDK, paste the following code block.
RequestResponseimport { usePageWidgets, Widget, PageWidgetsProvider } from "@sitecore-discover/react"; import MyRecommendationWidget from './widget_components/recommendation/widget'; import MyGlobalPreviewSearch from "./widget_components/myGlobalPreviewSearch"; import MyGlobalRecommendationWidget from "./widget_components/myGlobalRecommendationWidget"; import CustomPageWidgets from "./widget_components/customPageWidgets" const App = () => { return ( <div style={ theme.style } > <WidgetsProvider env='<environment>' customerKey='<customer key>' apiKey='<api key>' useToken > <header> <h1>My Application</h1> <MyGlobalPreviewSearch rfkId="header_ps" /> </header> <div class="content"> <PageWidgetsProvider> <CustomPageWidgetsComponent /> </PageWidgetsProvider> </div> <footer> <MyGlobalRecommendationWidget rfkId="footer_rec" /> </footer> </WidgetsProvider> </div> )}; export default App; -
At compile time, if errors are displayed, fix import statements to match locations and names.