ToDo App with WebComponents
Lets see WebComponents in action by building a ToDo App with WebComponents and ShadowDOM. This will build an understanding of using these in your Front End apps.
As we saw the basics of WebComponents, let see it in action and build a complete ToDo App with WebComponents. Here we will see some of the concepts around WebCompoents and Front-End App.
The benefits of WebComponents App are more or less similar to the benefits of React App; you are free to shape it in any way. So we will be taking React's jargon like props
, onClick
etc.
Let's dive in the code.
Primarily we have four components
- todo-application
- todo-form
- todo-list
- todo-task
Among these 4, the first one; todo-application
will be hosting everything inside the shadow-dom
.
For polyfill, we will be using the official one from webcomponents.org
https://cdnjs.cloudflare.com/ajax/libs/webcomponentsjs/1.0.22/custom-elements-es5-adapter.js
And for design, we will be using bootstrap 4 CSS.
The app is bundled together with the help of webpack and we will be using babel
to transpile our app to ES5 and raw-loader
to load css files.
module: { rules: [ { test: /\.css$/, use: 'raw-loader' }, { test: /\.js$/, exclude: /(node_modules)/, use: { loader: 'babel-loader', options: { presets: ['@babel/preset-env'], plugins: [], } } } ] },
As we have it all configured with webpack, lets get into the code for todo app
ToDo App
And template:
Primary things to notice in above code would be:
- initialize the base data
- attach a
shadowDOM
inopen
mode; you can read more about shadowDOM here - set the
innerHTML
ofshadowDOM
of its template - collect the
refs
; i.e. the main DOM elements of app - set the
props
on necessaryrefs
- define the custom element
For templating, we are using the ES6 template literals. You can read more about them here: https://time2hack.com/introduction-to-webcomponents-and-shadowdom/
Form
Following is the Component for form; the form's events are being set manually by the todo app controller after it is mounted be the app controller.
with following HTML as ES6 template:
List
The List component will receive the object and will use the todo-task
component. Here is the component:
And the HTML template for above component:
Task
Following the individual task component which will also handle the completion and depletion of the task:
And the HTML template for above component:
Checkout the code and demo here: