So if you wanted to create a component based architecture on your project, what could you do?

Well, let’s say you have some static HTML in your index.html, like so:

And you want to do stuff with the js-app div. You could just fetch it with a query selector, and change it manually. But let’s say you want to use a more component based approach (because components are all the rage these days). You could write something like this in your index.js file:

We create a JavaScript class, and pass in the js-app class name to its constructor. This fetches the correct element with the query selector on line 3, and saves it in the context variable of the class instance.

Here’s a link to this example on code-sandbox.

So why did we do this? It seems like overkill for just changing the inner HTML of a div.

Well, if we structure our code like this, we can combine components pretty easily. Let’s say we have a username/password form like so:

Let’s say we want to add some validation to these inputs, so they turn red when the fields are empty. We could add the following css and js code to make it work, in line with the previous example:

The css is just changing the background color, so it indicates which input is erroneous.

The js contains a class, which gets instantiated twice at the bottom of the file. Once for the login input element, and once for the password input element. so both of these instances are separate from each other, and have their own event handlers.

We add a couple of event handlers — one which gets triggered as soon as the user starts typing (onChange), and another one which gets triggered when the user leaves the input (onBlur). We only show the error background if the user un-focuses the input element, and the content of the element is empty.

Here’s the link to the example in code-sandbox.

And so, we have a simple form, with some validation on it, just using native JavaScript. We also structured the code in a more component oriented way. We could also go a step further and extract the RequiredInput class to it’s own file, and import it, instantiate it, or extend it as necessary, so this approach can be quite flexible.