Conditionally Mount the Widget
Create a file for the widget’s “create” function.
touch src/applications/static-pages/hello-world/createHelloWorldWidget.js
Add the following contents to the file:
import React from "react";
import ReactDOM from "react-dom";
import widgetTypes from "../widgetTypes";
export const createHelloWorldWidget = async () => {
const container = document.querySelector(
`div[data-widget-type="${widgetTypes.HELLO_WORLD}"]`
);
if (!container) {
return;
}
const { HelloWorldWidget } = await import(
/* webpackChunkName: "hello-world" */ "./components/HelloWorldWidget"
);
ReactDOM.render(<HelloWorldWidget />, container);
};
The above code:
- Exports a single function called
createHelloWorldWidget - This function searches for a
<div>with thedata-widget-typeattribute whose value is the unique string you added to thewidgetTypesobject (HELLO_WORLD) - If the
<div>is not found, the function does nothing - Otherwise, the function imports the
HelloWorldWidgetbundle, which contains theHelloWorldWidgetReact component, and then mounts the component into the<div>.