5 Ways To Create Reusable Javascript Components (Simple Examples)

Welcome to a tutorial on how to create reusable Javascript Components. Back in the school days, lecturers often preached about reusability in object-oriented programming. But the sad part is that they have never gone into the proper details of how to do it. So here it is, let us walk through some common ways to build reusable components in Javascript – Read on!

 

 

TABLE OF CONTENTS

Download & Notes The Basics Reusable Components
Useful Bits The End

 

DOWNLOAD & NOTES

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

 

QUICK NOTES

If you spot a bug, feel free to comment below. I try to answer short 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.

 

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.

 

 

REUSABLE COMPONENT BASICS

Before we go into the examples of building reusable components, let us quickly recap 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”.
  • Maybe as a “widget” and “plugin”.
  • Perhaps even a “library”.

Everyone has their own perspective 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 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. Object – Group all functions and properties into an object.
  2. Class – Good old object-oriented programming.
  3. Encapsulated Anonymous Function – A rather funky way to create a library.
  4. Modules – Import, export, or require in the “NodeJS way”.
  5. Web Components – Build your own reusable HTML elements. Some of you guys should have already heard of some of these – React, Angular, Lit.

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

 

 

BUILDING REUSABLE COMPONENTS

The “caveman” way to create reusable components, is 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.

 

METHOD 1) OBJECT

1A) COLLECTION OF FUNCTIONS

1a-mylib.js
var mylib = {
  // (A) AJAX : DO A POST AJAX CALL
  // url : target url
  // done : function to call when server responds
  ajax : (url, done) => {
    fetch(url, { method:"POST", body:form })
    .then((res) => { return res.text(); })
    .then((txt) => { done(txt); });
  },
 
  // (B) LOAD : USE AJAX TO LOAD CONTENTS
  // url : target url
  // target : id of target html element
  load : (url, target) => {
    mylib.ajax(url, (txt) => {
      document.getElementById(target).innerHTML = txt;
    });
  }
};

This may seem intimidating to some beginners, but keep calm and look carefully.

  • Start by creating an object. Here, we have var mylib = {}.
  • Simply append all the reusable functions into the object.
    • mylib.ajax() Does a simple AJAX fetch() call.
    • mylib.load() Rides on top of mylib.ajax(), puts the server response into a specified HTML element.

Yes, that’s all. All we are doing here is to sandwich functions in an object. This is easier to manage than having a ton of functions all over the place.

 

1B) USAGE EXAMPLE

1b-demo.html
<!-- (A) LOAD LIBRARY -->
<script src="1a-mylib.js"></script>
 
<!-- (B) AJAX LOAD CONTENT -->
<div id="demo"></div>
 
<script>
mylib.load("1c-dummy.html", "demo");
</script>
1c-dummy.html
<strong>It Works!</strong>

With that, we have a simple library that has a reusable AJAX call function to load HTML contents.

 

 

METHOD 2) CLASS

2A) CLASS LIBRARY

2a-mylib.js
class Mylib {
  // (A) AJAX : AJAX FETCH
  // url : target url
  // done : function to call when server responds
  ajax (url, done) {
    fetch(url, { method:"POST" })
    .then((res) => { return res.text(); })
    .then((txt) => { done(txt); });
  }
 
  // (B) LOAD : USE AJAX TO LOAD CONTENTS
  // url : target url
  // target : id of target html element
  load (url, target) {
    this.ajax(url, (txt) => {
      document.getElementById(target).innerHTML = txt;
    });
  }
}

If you prefer the “proper object-oriented way”, we can also create a class library in Javascript.

 

2B) USAGE EXAMPLE

2b-demo.html
<!-- (A) LOAD LIBRARY -->
<script src="2a-mylib.js"></script>
 
<!-- (B) AJAX LOAD CONTENT -->
<div id="demo"></div>
 
<script>
var mylib = new Mylib();
mylib.load("1c-dummy.html", "demo");
</script>

Create a new Mylib() object, use the library functions. The end.

 

METHOD 3) ENCAPSULATED FUNCTION

3A) FUNKY ANONYMOUS FUNCTION

3a-mylib.js
(() => {
  // (A) AJAX : AJAX FETCH
  // url : target url
  // done : function to call when server responds
  var ajax = (url, done) => {
    fetch(url, { method:"POST" })
    .then((res) => { return res.text(); })
    .then((txt) => { done(txt); });
  };
 
  // (B) LOAD : USE AJAX TO LOAD CONTENTS
  // url : target url
  // target : id of target html element
  var load = (url, target) => {
    ajax(url, (txt) => {
      document.getElementById(target).innerHTML = txt;
    });
  };
 
  // (C) "PUBLIC FUNCTIONS"
  window.mylib = { load : load };
})();

If your reaction is WTF, you are not alone. I was confused when I first learned about this way of creating libraries.

  • First, we have a “regular anonymous arrow function” (a function without a name) – () => {}
  • Then, encapsulate it in round brackets – ( () => {} )
  • Lastly, we run the encapsulated anonymous function – ( () => {} ) ()

So why go through all the confusing hassle? Abstraction.

  • There are 2 functions here as usual – ajax() and load().
  • But take note of window.mylib = { load : load }, only mylib.load() is accessible.
  • That is, ajax() is locked inside the anonymous function, and there is no way to call it publically.

 

 

METHOD 4) JAVASCRIPT MODULES

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

Not going to dive deep into this one, as it will 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. It basically allows us to import/export Javascript functions and variables as modules.

 

METHOD 5) 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.

 

WHICH IS THE BEST METHOD?

Personally, I lean towards “object library”. It is straightforward and easy to maintain. But there’s nothing wrong with all the other methods too, even for methods that are not mentioned in this guide – Whatever works for you is the best method.

 

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.