3 Ways To Create Reusable Javascript Components – Simple Examples

Welcome to a tutorial on how to create reusable Javascript Components. Back in the school days, one of the first things that lecturers taught about object-oriented programming is code reusability. But the sad part is that they have never gone into the proper details of how to do it, despite preaching it many times.

So here it is, I have finally figured some things about being lazy and “reusability” after donkey years of being a web developer. In this guide, I shall share my way of building reusable components – Read on!

 

 

TABLE OF CONTENTS

Download & Notes The Basics How to Build
Useful Bits The End

 

DOWNLOAD & NOTES

Firstly, here is the download link to the example code as promised.

 

EXAMPLE CODE DOWNLOAD

Click here to download the source code, I have released it under the MIT license, so feel free to build on top of it or use it in your own project.

 

QUICK NOTES

If you spot a bug, please feel free to comment below. I try to answer questions too, but it is one person versus the entire world… If you need answers urgently, please check out my list of websites to get help with programming.

 

 

REUSABLE COMPONENT BASICS

Before we go into the examples of building reusable components, let us quickly walk through some of the basics.

 

WHAT ARE REUSABLE COMPONENTS?

Have you written functions before? If yes, then well done. You have already created a simple version of a reusable component. But some angry trolls are going to disagree, and it is all right to do so. The term “reusable component” can be very subjective today.

  • To some people, it can mean a “framework”.
  • Or a “module”.
  • Perhaps even a “library”.

Everyone has their own perspective and idea of what a “reusable component” should be. But I think in the simplest manner – So long as a piece of Javascript code can be reused and applied in different areas, I will consider it to be a (simple) reusable component.

 

MANY WAYS TO CREATE REUSABLE COMPONENTS

There are probably endless ways to create reusable components in Javascript. But let me do a quick compilation and generalization:

  1. The “traditional way” – Grouping functions and objects together.
  2. Javascript Modules – Importing and exporting, or require in the “NodeJS way”.
  3. Web Components – Building your own reusable HTML elements. Check out Lit, and some of you guys should already know – Angular.

As to which one is “correct” – All of them are, you decide for yourself which is the best way.

 

 

BUILDING REUSABLE COMPONENTS

The most “caveman” way to create reusable components is pretty much to write a thousand functions, and stash them into a single JS file… But let us take a look at more elegant ways of doing it.

 

1) “TRADITIONAL” COMPONENTS

1A) BASIC IDEA

1a-native.js
var _BB = {
  // (A) AJAX : DO A POST AJAX CALL
  // URL : TARGET URL
  // DATA : OPTIONAL, DATA TO SEND
  // DONE : OPTIONAL, FUNCTION TO CALL WHEN SERVER RESPONDS
  ajax : function (url, data, done) {
    // (A1) FORM DATA
    var fd = null;
    if (data) {
      fd = new FormData();
      for (let i in data) { fd.append(i, data[i]); }
    }
 
    // (A2) AJAX CALL
    var xhr = new XMLHttpRequest();
    xhr.open("POST", url);
    if (typeof(done) == "function") { xhr.onload = done; }
    xhr.send(fd);
  }
};

Look no further, this is as simple as it gets:

  • Start by creating an object, I shall call this library/module/framework/component “Base Boxx”. To keep it simple, var _BB = {}.
  • Append all the reusable functions in the object. Yes, we shall start with a simple AJAX call function – _BB.ajax().

 

1B) USAGE EXAMPLE

1b-native.html
<!-- (A) LOAD CORE -->
<script src="1a-native.js"></script>
 
<!-- (B) AJAX LOAD CONTENT -->
<div id="demo"></div>
<script>
_BB.ajax(
  "1c-dummy.html", null,
  function () {
    document.getElementById("demo").innerHTML = this.response;
  }
);
</script>
1c-dummy.html
<strong>It Works!</strong>

With that, we have created a library that has a reusable AJAX call component – Use it to load contents, submit forms, and whatever else.

 

1C) EXTENDING THE LIBRARY & FUNCTIONS

The above example is still pretty raw. Let us add another function to further simplify the “get contents via AJAX and put into HTML element”.

1a-native.html
// (B) AJCON : USE AJAX TO LOAD CONTENTS
// URL : TARGET URL
// TARGET : ID OF TARGET HTML ELEMENT
// DATA : OPTIONAL, DATA TO SEND
ajcon : function (url, target, data) {
  this.ajax(url, data, function () {
    document.getElementById(target).innerHTML = this.response;
  });
} 

Now that becomes:

1d-native.html
<div id="demo"></div>
<script>
_BB.ajcon("1c-dummy.html", "demo");
</script>

Yep, that’s what we call “lazy and reusable”… But lazy in a clever way.

 

 

1D) FUTURE DEVELOPMENT

I think you catch the drift – We simply add more useful functions to the library over time. But the library will grow massive eventually, you will want to further split the library into different files. For example:

  • base-boxx.js remains as the core.
  • Split all the UI functions into an optional base-boxx-ui.js_BB.UI = { FUNCTIONS };

 

2) JAVASCRIPT MODULES

Not going to dive deep into this one, as it is going to become a really long tutorial. I shall leave a link below if you are interested to learn more. But as a quick introduction – Javascript Modules are introduced in ES5. Basically, it allows us to import/export Javascript functions and variables as modules. For example:

2a-module.js
export function first () { alert('first!') }
export function second () { alert('second!') }
2b-module.html
<script type="module">
import * as _BB from "./2a-module.js";
_BB.first();
_BB.second();
</script>

Modules have increasingly become popular, good to at least take a look and know the basics.

 

 

3) WEB COMPONENTS

Lastly, we have something called “web components”. Basically, create our own reusable custom HTML elements, maybe something like this:

<datepicker max="+1 year" min="today" id="myPicker"></datepicker>

Not going to dive deep again, as this is quite a deep and advanced topic. Also, this is not quite a “Javascript component”. More of a cross between HTML, CSS, and Javascript.

 

USEFUL BITS & LINKS

That’s all for the tutorial, and here is a small section on some extras and links that may be useful to you.

 

NOT PERFECT

Before the haters spew poison again – This is ultimately a “simple example” guide. This is not meant to confuse beginners with the deep advanced stuff, but to provide a general starting point – There are endless ways to create “reusable components”, only you can decide for yourself which is the best.

 

LINKS & REFERENCES

 

THE END

Thank you for reading, and we have come to the end. I hope that it has helped you to better understand, and if you want to share anything with this guide, please feel free to comment below. Good luck and happy coding!

Leave a Comment

Your email address will not be published. Required fields are marked *