2
\$\begingroup\$

beginner web dev here. I created a custom list component (with edit feature) in plain JS/HTML.

I have few questions on which I would like to get an answer (besides the normal feedback that you folks do here on the site):

  • is this a standard/right way to create and use components when using plain JS?

  • if I can create and use objects like this, what is the benefit of creating such component using say react.js?

ListComponent.js

///////
//
// ListComponent is a class which lets you create a list component
// dynamically using JS and DOM. The list component also has some features
// out of the box - e.g. editing items when clicked.
//
function ListComponent(type) {

    // Model data of the list.
    this.data = [{ name: "mona", id: 0 }, { name: "dona", id: 1 }, { name: "jona", id: 2 }],

    // Create a list component.
    this.create = function () {
        let list = document.createElement(!type ? "ul" : type);
        list.id = "customList";
        document.body.appendChild(list);
        this.draw();
    },

    this.remove = function () {
        // Remove our list component from DOM
        var elem = document.getElementById("customList");
        return elem.parentNode.removeChild(elem);

    }

    ///
    // draw
    //  Appends items to the list component.
    //  Deletes any child items first if there are any.
    //
    this.draw = function () {
        let that = this;

        // First delete all items of the list.
        let list = document.getElementById("customList");
        while (list.firstChild) {
            list.removeChild(list.firstChild);
        }

        // Now, append new items.
        that.data.forEach(function (item) {
            let listItem = document.createElement("li");

            // Listen to click event on this list item.
            listItem.addEventListener("click", function () {
                let newName = prompt("Enter item name", item.name);
                if (newName == null || newName.length == 0)
                    return;

                // Make change in the list model data.
                for (let i = 0; i < that.data.length; i++) {
                    if (that.data[i].id == item.id) {
                        that.data[i].name = newName;
                        break;
                    }
                }

                // Redraw the list.
                that.draw();
            }, false);

            listItem.innerHTML = item.name;
            listItem.id = item.id;
            list.appendChild(listItem);

        });
    }
}

index.html

<!doctype html>

<html lang="en">

<head>
    <meta charset="utf-8">
    <title>Demo site</title>
    <!-- Import our list component -->
    <script src="ListComponent.js"></script>
</head>

<script>

    document.addEventListener("DOMContentLoaded", function (event) {
        // Run this code when DOM is loaded.
        let list = new ListComponent("ol");
        list.create();    
    });

</script>

</body>

</html>
\$\endgroup\$
1
\$\begingroup\$

is this a standard/right way to create and use components when using plain JS?

It's not technically wrong, but when you're writing re-usable components it's better to use prototype than to create methods in the constructor itself.

For example,

function listComponent(){}
listComponent.prototype.create = function() { .. };
listComponent.prototype.remove = function(){ ... };
listComponent.prototype.draw = function(){ ... };

When you create the methods inside the constructor then those methods are duplicated in memory for every object created. When you use the prototype those methods only need to be defined once.

If you want to write code that feels like a class then use an actual class. (JS has those now).

Aside from that, don't store you data in the function that creates the list. Pass the data into the constructor or create method.

if I can create and use objects like this, what is the benefit of creating such component using say react.js?

If all you need is to generate a simple list then there is no reason to use react. React has a lot of components that your code doesn't have, like interactive features, etc.

If you take a few minutes to read about exactly what react is and does the answer to this question will be clear.

\$\endgroup\$
  • \$\begingroup\$ I've read those react docs but benefits as compared to approach in this question is still not that clear. apart from some custom made react components which could exist of course. Speed because of virtual DOM? anything else? \$\endgroup\$ – user145353 Jul 28 '17 at 18:11
  • \$\begingroup\$ @user200300 - From my answer: If all you need is to generate a simple list then there is no reason to use react. - In other words, compared to the approach given in the question there is no benefit to using react. \$\endgroup\$ – I wrestled a bear once. Jul 28 '17 at 18:12
  • \$\begingroup\$ I meant benefits in in general not only in this case. (see my prev. comment). \$\endgroup\$ – user145353 Jul 28 '17 at 18:38
  • \$\begingroup\$ @user200300 Explaining what a certain library does is out of the scope of Code Review. See my last paragraph :) \$\endgroup\$ – I wrestled a bear once. Jul 28 '17 at 18:44
0
\$\begingroup\$

is this a standard/right way to create and use components when using plain JS?

There are best practices as well as opinionated approaches, but no standard way of doing stuff. The language is very flexible that it allows different paradigms. It's up to you how you do it.

if I can create and use objects like this, what is the benefit of creating such component using say react.js?

The primary benefit of frameworks is to let you focus less on mundane tasks like rendering, routing, state management etc. and focus more on what matters most: your app. Most frameworks are high-level enough that all you ever worry about is your template and data.

A good example to visualize this is Svelte, a framework that takes your framework code and compiles it to raw, runtime-less, JS. It has a REPL that shows you a good example of what you write when using a framework versus what you'd have to write every time if you didn't use one (click the "Input" button below to toggle between input and output).

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy