Websites are often built in such a way that a large part is occupied by static content, which is rarely changed over a period of time, along with very concentrated functionalities, which receive improvements, enhancements and fixes on a regular basis.
It is such scenarios that are very good use-cases for deriving value from a website using a ‘widgetized’ UI-rendering and development strategy.
With this post, I would like to share how our team at Coverfox.com have implemented this strategy and use it on a day-to-day basis for easily adding and using ‘widgets’ on the website.
First, we need to define which all components qualify as Widget. These are components which generally work in a standalone manner and serve a definitive business purpose. Once we’ve identified all such components, we need to find a way for our code to recognize these widgets.
One way to classify a widget is to give the widget module a specific nomenclature. Once the nomenclature is decided, we can use Webpack’s require.context method to iterate over a set of modules (based on their file-path) and prepare a map of all possible widgets.
The Gist below gives an example of how this can be done considering a widget-module’s name is of the format widget-name.widget.jsx and all our widgets are located inside src directory.
The Gist below takes care of this by using this map of Widgets. The method getLazyComponent takes in widget-name and other relevant details and returns a React.Component class object.
Note: Since we’ll be using bundle-loader, the entries in widgetMap returns an asynchronous function for every valid widget-name. This function expects a callback as a parameter. The callback receives the value of widget-module’s export in it’s first argument.
Next, we need a global utility to render these asynchronously loaded components for us. This can be archived simply by using ReactDOM’s render method.
Take a look at the Gist below.
The BUNDLE_LOADER_RULES constant in below Gist takes care of packaging different Widgets and there dependant modules in specific bundles based on there file paths.
Refer to the Gist below. You can also find a working example here.
Thanks for reading. Let us know your thoughts on this. Also, don’t forget to visit Coverfox.com for all your insurance needs.