Skip to main content
Skip table of contents

Creating a new React widget

Widgets are features that implement dynamic behavior in a contained section of a page. This document shows how to write widgets in React and add them to a static page.

Check out the Adding a new feature doc to make sure you're trying to add the right type of feature to VA.gov.

Guidelines for using React on a static page

We should be careful to not create a bad user experience when using React on static pages. Here are some guidelines you should follow:

  1. JS and React take time to download, parse, and render. Make sure you are providing the appropriate feedback to users while that is happening, with a spinner or another method from the UX team.

  2. Make sure the page is still usable if your React code fails to work. This can mean it fails to download, an error occurs, or just handling the different login states a user can be in.

  3. Be aware of how much weight you're adding to the static-pages bundle and code-split/lazy load when it makes sense.

Adding a new widget

  1. Add widget of widgetType: “my-widget-name” to src/applications/registry.scaffold.json:

CODE
{
    "appName": "My Application",
    "rootUrl": "/my-root-url",
    "widgetType": "my-widget-name"
}
  1. Add MY_WIDGET_NAME type to src/applications/static-pages/widgetTypes.js.
    MY_WIDGET_NAME: 'my-widget-name',

  2. If it doesn't already exist, create src/applications/static-pages/my-feature for housing (and testing) component logic. Within my-feature you may define your own folder structure, but one common pattern is my-feature/components/App.

  3. Add start up function to src/applications/static-pages/my-feature/index.js:

CODE
export default (store, widgetType) => {
  const root = document.querySelector(`[data-widget-type="${widgetType}"]`);
  if (root) {
    import(/* webpackChunkName: "my-widget-name" */
    './components/App').then(module => {
      const App = module.default;
      connectFeatureToggle(store.dispatch);

      ReactDOM.render(
        <Provider store={store}>
          <App />
        </Provider>,
        root,
      );
    });
  }
};
  1. Import and run createMyWidgetName in src/applications/static-pages/static-pages-entry.js:
    createMyWidgetName(store, widgetTypes.MY_WIDGET_NAME);

  2. The widget may be added as a mount point element in a static content page like so:
    <div data-widget-type="my-new-widget" id="someId"></div>

Generally the Sitewide CAIA team is responsible for adding react widgets to a Drupal page. The Sitewide CAIA team will need to be provided with the widgetType defined in Step 1.


JavaScript errors detected

Please note, these errors can depend on your browser setup.

If this problem persists, please contact our support.