Category: JavaScript

Understanding Angular lifecycle methods with Examples

In Angular, components have a lifecycle managed by Angular itself, from creation to destruction. Angular provides lifecycle methods that you can use to tap into this process and perform custom logic at specific points in the lifecycle.

Here are some examples of how you might use each lifecycle method:

ngOnChanges: This method is called whenever a bound input property changes. You can use it to react to changes in input properties and perform logic when the value of an input property changes.

import { Component, Input, OnChanges } from '@angular/core';

@Component({
  selector: 'app-counter',
  template: '<p>{{counter}}</p>'
})
export class CounterComponent implements OnChanges {
  @Input() counter: number;

  ngOnChanges(changes: SimpleChanges) {
    console.log(changes);
  }
}

In this example, the CounterComponent implements the ngOnChanges method and logs the changes to its input properties.

  1. ngOnInit: This method is called after the first ngOnChanges call and is used to perform initialization logic for the component.
import { Component, OnInit } from '@angular/core';

@Component({
  selector: 'app-hello',
  template: '<p>Hello, {{name}}!</p>'
})
export class HelloComponent implements OnInit {
  name: string;

  ngOnInit() {
    this.name = 'Angular';
  }
}

In this example, the HelloComponent implements the ngOnInit method and initializes its name property.

  1. ngDoCheck: This method is called during every Angular change detection cycle and is used to perform custom change detection.
import { Component, DoCheck } from '@angular/core';

@Component({
  selector: 'app-todo-list',
  template: `
    <ul>
      <li *ngFor="let item of items">{{item}}</li>
    </ul>
  `
})
export class TodoListComponent implements DoCheck {
  items: string[];

  ngDoCheck() {
    console.log(this.items);
  }
}

In this example, the TodoListComponent implements the ngDoCheck method and logs its items array.

  1. ngAfterContentInit: This method is called after the component’s content has been fully initialized.
import { Component, AfterContentInit } from '@angular/core';

@Component({
  selector: 'app-tabs',
  template: `
    <ng-content></ng-content>
  `
})
export class TabsComponent implements AfterContentInit {
  ngAfterContentInit() {
    console.log('Tabs content initialized');
  }
}

In this example, the TabsComponent implements the ngAfterContentInit method and logs a message to the console.

  1. ngAfterContentChecked: This method is called after every change detection cycle that updates the component’s content. It can be used to perform logic that depends on the component’s content being fully updated and checked.
import { Component, AfterContentChecked } from '@angular/core';

@Component({
  selector: 'app-tabs',
  template: `
    <ng-content></ng-content>
  `
})
export class TabsComponent implements AfterContentChecked {
  ngAfterContentChecked() {
    console.log('Tabs content checked');
  }
}

In this example, the TabsComponent implements the ngAfterContentChecked method and logs a message to the console.

6. ngAfterViewInit: This method is called after the component’s view (including its child views) has been fully initialized.

import { Component, AfterViewInit } from '@angular/core';

@Component({
  selector: 'app-tab-panel',
  template: `
    <ng-content></ng-content>
  `
})
export class TabPanelComponent implements AfterViewInit {
  ngAfterViewInit() {
    console.log('Tab panel view initialized');
  }
}

In this example, the TabPanelComponent implements the ngAfterViewInit method and logs a message to the console.

7. ngAfterViewChecked: This method is called after every change detection cycle that updates the component’s view (including its child views).

import { Component, AfterViewChecked } from '@angular/core';

@Component({
  selector: 'app-tab-list',
  template: `
    <ng-content></ng-content>
  `
})
export class TabListComponent implements AfterViewChecked {
  ngAfterViewChecked() {
    console.log('Tab list view checked');
  }
}

In this example, the TabListComponent implements the ngAfterViewChecked method and logs a message to the console.

8. ngOnDestroy: This method is called just before the component is destroyed by Angular. It can be used to perform cleanup logic for the component, such as unsubscribing from observables or detaching event handlers.

import { Component, OnDestroy } from '@angular/core';

@Component({
  selector: 'app-timer',
  template: '<p>{{time}}</p>'
})
export class TimerComponent implements OnDestroy {
  time: number;
  intervalId: number;

  ngOnInit() {
    this.intervalId = setInterval(() => {
      this.time = Date.now();
    }, 1000);
  }

  ngOnDestroy() {
    clearInterval(this.intervalId);
  }
}

In this example, the TimerComponent implements the ngOnDestroy method and uses it to stop the interval timer it started in its ngOnInit method.

I hope you found this article useful and informative. Thanks 😊

Creating a Vue.JS Instance Using its Fundamental Concepts

Vue.js is simple and powerful, and it is easy to learn. Once you understand the basics of the framework, everything will work in just the way you expect. The framework will help you to keep focused on writing the logic of your application instead of remembering a bunch of APIs that are hard to use. This article will help you learn some of the fundamental concepts in Vue.js.

Fundamental concepts

When you start a Vue application, what you need to keep in mind is your application’s logic itself. You don’t need to remember a set of APIs so that you can connect different pieces of your code. Vue.js, which is a progressive framework, provides you with an intuitive way of writing web applications, starting small and growing incrementally into a large-scale application. If you have used other frameworks before, you may wonder why they make things unnecessarily complicated. Now, let’s go through fundamental concepts in Vue.js and create a sample application. You can also access the complete code for this article at https://github.com/PacktPublishing/Building-Applications-with-Spring-5-and-Vue.js-2/tree/master/Chapter02/MessagesApp.

Creating a Vue instance

Creating a Vue instance is the start of every Vue.js application. Typically, a Vue application consists of two types of Vue instance—the root Vue instance and component instances. You create the root instance with the Vue function, as follows:

new Vue({/* options */});

The options object here is where you describe your application. Vue.js takes this object and initializes the Vue instance. Let’s create a simple application, called the Messages App and see how to use the options object. This SPA has the following features:

  • Add a message
  • View messages list
  • Delete a message
  • Automatically disable the add feature under certain conditions

We will start by creating the index.html file and, from there; we will build our application incrementally. Let’s have a look at the index.html file:

1.<!DOCTYPE html>
2.<html>
3.<head><title>Messages App</title></head>
4.<body>
5.
6.https://unpkg.com/vue@2.5.13/dist/vue.js 7. 8.let vm = new Vue({ 9.el: '#app' 10. }); 11. 12. </body> 13. </html>

In line 5, we create a 

 element with an app id in the DOM. And in line 9, we mount our application to this element by using the el property of the options object. el is short for element, and its value can be a CSS selector string, like the one we use here, '#app', or it can be the HTMLElement itself, document.getElementById('app'). In line 8, we assign the Vue instance to the vm variable, which is short for ViewModel.

Now, let’s define our data model of the application. We need an array to hold those added messages and a string to bind to the form’s input which will accept new messages. Here is how the data object appears:

...
let vm = new Vue({
el: '#app',
data: {
    messages: [],
newMessage: ''
}
});
...

We add the data object using object literals. As you can see, it is quite straightforward. We give them initial values so that you can easily tell that messages is an array and newMessage is a string. Providing initial values for the data object properties is a good practice. It not only helps you understand the data model better, but also makes those properties reactive by default. 

Besides using a plain object as the value of the data property of the options object, you can also use a function that returns a plain object, as in the example:

...
data () {
  return {
    messages: [],
    newMessage: ''
  }
}
...

Using a function is required when you define the data structure for a component because, in that way, Vue.js will always create a fresh data model for the new component. If you use a plain object to define a component’s data model, all of the instances of that component will share the same data object, which is not desired. For our root Vue instance here, we are safe to use a plain object.

For now, we have only defined the data model, and we haven’t told Vue.js what to do with the data object. Let’s add a template for displaying and adding messages. You can add a template in three ways. One is to add an inline template string using the template property of the options object. It is appropriate to adopt this approach when you create a component that doesn’t have a lot of markups.

The second way is to put the template directly inside the mounting point, 

. Vue.js will parse the template inside #app and replace it with HTML generated by Vue.js. The third way is to put the template markup inside a script tag, for example, <script type="x-template" id="tmplApp">, and put '#tmplApp' as the value of the template property of the options object. We will adopt the second approach here just so we can have the template markup close to the final output. Here is how the template appears:

... 
5.
6.
    7.
  • 8. {{ message.text }} - {{ message.createdAt }} 9.
  • 10.
11. 12. 14.
15. </form> 16. </div> ...

In line 7, we use the Vue built-inv-for directive to render the messages list. The syntax of the v-for directive is alias in source. In our code, message is alias and messages is source. We don’t need to write vm.messages in order to access the messages property. Just use the exact name that you put in the data object. And by adding the v-for directive to the li tag, we create a v-for block inside the li tag, and that’s where thealias message will be available. You can think of the v-for block as being equivalent to the for-loop block in JavaScript.

In line 8, we use Mustache syntax to output the text property and createdAt property of a message object of the messages list. The createdAt property is a Date object that we add when saving a new message. When Vue.js parses the template and interpolates a Mustache tag, for example, {{message.text}}, it creates data binding between the output and the data. It will replace the tag with the actual value and update the output whenever the text property has been changed. The text interpolation also supports JavaScript expression. For example, you can make the text property always in lower case with {{message.text.toLowerCase()}}.

In line 11, we use another built-in directive, v-on, to attach an event listener to the form’s submitevent.prevent is a modifier, telling Vue.js to call event.preventDefault() so that the browser won’t actually submit the form. addMessage is a method that will be invoked when the form’s submit event is triggered. We will create this method shortly. You can use v-on to attach listeners to all of the normal DOM events, for example, click and mouseover. You can also use it to listen to custom events of Vue’s custom components in the same way. We will see how that works shortly.

In line 12, we use the built-inv-model directive to create a two-way binding between the textarea element and newMessage property of the data object. In this way, whenever the value of the textarea element is changed, the newMessage will be updated automatically. And when newMessage is changed, textarea will be updated accordingly. This is such a nice feature that you can get the value of the textarea element without touching it yourself specifically. It works just as you would imagine it should.

In line 14, we add a button with type="submit" to trigger the submit event of the form. Now, let’s create our addMessage method to listen to that event. We can do it by using the methods property of the options object.

Here is how the options object appears with the addMessage method:

...
let vm = new Vue({
...
data: {
...
},
methods: {
addMessage (event) {
if (!this.newMessage) {return;}
this.messages.push({
text: this.newMessage, createdAt: new Date()});
this.newMessage = '';
}
}
});
...

The methods property of the options object takes an object, where you put all of your methods. And inside these methods, you have access to the properties of the data object via this, as you can see that we use this.newMessage and this.messages inside the addMessage method to access them. The method syntax we use here is ES6, but you can also use function expression, as follows:

addMessage: function (event) {
  // Logic goes here
}

However, you should not use arrow functions syntax to create methods because you will lose access to the Vue instance via this.

Inside the addMessage method, we add the new message to the messages array using the push() method, and then we reset the newMessage property. Accordingly, Vue.js will clear textarea in the UI automatically. This is the magic of two-way binding, which will be revealed soon.

Now, let’s add a way to delete a message from the UI. Here is what we change in the template:

...
<li v-for="message in messages">
{{ message.text }} - {{ message.createdAt }} 
<button @click="deleteMessage(message)">X</button>
</li>
...

We add a button and use @click, the short-hand of v-on:click, to attach the listener deleteMessage method to the click event. Instead of putting the method’s name here, we use an inline statement to pass the message object to the method. And here are the updated methods of the options object:

...
let vm = new Vue({
... 
methods: {
...
deleteMessage (message) {
this.messages.splice(this.messages.indexOf(message), 1)
}
}
});
...

We delete the selected message from the messages array using the Array.prototype.splice() method. Vue.js will detect this change and update the DOM automatically. You don’t need to manipulate the DOM at all.

Now, let’s add the ability to automatically disable the add feature. Let’s say we want to disable the Add button when there are 10 messages in the list. To do that, we can use the built-in v-bind directive to bind the Add button’s disabled attribute with the messages.length >= 10 expression. In this way, Vue.js will update the disabled attribute automatically when the length of the messages array changes. Here is the updated template:

...
<form @submit.prevent="addMessage">
...
</form> ...

What if we want to change the logic so that the Add button is disabled when the length of the textarea input exceeds 50 characters? You will need to change the value of the v-bind directive to newMessage.length > 50. What if we want to disable the button when there are already 10 messages, or the length of newMessage exceeds 50 characters? We can change the directive value to messages.length >= 10 || newMessage.length > 50. It still works. However, as you can see, the code starts to bloat and it would become hard to maintain when you need to add more logic to decide when the Add button should be disabled.

Here, we can use computed properties. As the name suggests, the value of such a property is computed rather than defined as those in the data object. And Vue.js will track the dependencies of a computed property and update the property’s value when the dependencies change. Let’s add the computed property addDisabled to the options object:

let vm = new Vue({
data {
...
},
computed: { 
addDisabled () {
return this.messages.length >= 10 || this.newMessage.length > 50;
}
},
... 
});

As you can see, the addDisabled computed property is defined as a method of the computed object of the options object. Inside the method, you also have access to the Vue instance via this. For the v-bind directive, there is also a shorthand option, which is a colon (:). Let’s update the Add button in the template to the following:

<button :disabled="addDisabled" type="submit">Add</button>

As you can see, our template becomes much easier to follow and maintain since you keep most of the logic in the JavaScript rather than in the HTML template. 

For the v-bind directive, you can use it to bind the HTML element’s built-in attributes, for example, class and style. You can also use it to bind a Vue’s custom component property. We will see how that works shortly.

By now, we have implemented all of the features of the Messages App. Since we didn’t use <script type="module">, you can open index.html directly using Chrome. If you try it now, you will see something strange. Immediately after opening the file, you can see the template markups that we put inside the mounting point, 

, which is awkward. The reason that it behaves in this way is that, before the browser loads Vue.js and executes it, it will display the HTML in the manner it is defined until Vue.js takes control of the DOM and removes the template markups from the mounting point and then replaces it with the new dynamically generated DOM. Let’s fix this by adding the v-cloak directive to the mounting point and inserting a CSS rule to hide the template markups. Vue.js will remove the v-clock directive when the generated DOM is ready. The following are the updates to the index.html file:


...

[v-cloak] {display: none;}
body > div {width: 500px; margin: 0 auto;}
textarea {width: 100%;}
ul {padding: 0 15px;}



...
</body>

Besides the [v-cloak] CSS rule, we add a few other rules to style the UI a little bit, even though it is still very primitive with these rules. Now, if you open it again in the browser, there is no flash anymore. 

By now, you’ve learned how to use the data object, the computed object, and the methods object of the options object of a Vue instance. And you can see that, even though the properties of these objects are defined separately, you can access them in the same way, which is via this

Now, let’s open the Console tab of Chrome’s Developer tools. Instead of using the input field in the UI, let’s add a new message from the console by interacting directly with the vm object, which is the root Vue instance that we created and made available in the global scope. As you can see from the following screenshot, it works as you would expect. This is its simplicity and powerfulness:


The Messages App in Chrome

Apart from the datacomputed, and methods properties, the options object has many other properties that you can use to define a Vue instance.

If you found this article interesting, you can explore Building Applications with Spring 5 and Vue.js 2 to Become efficient in both frontend and backend web development with Spring and Vue. With the help of Building Applications with Spring 5 and Vue.js 2 you’ll get to grips with Spring 5 and Vue.js 2 as you learn how to develop a web application.

Components in Blazor

Blazor is a component-based framework. In that component is defined as a block of the UI, consisting of both HTML and the corresponding business logic. The HTML helps to render the component on the web page, and the logic handles the database operations or the event handling. A Blazor component is lightweight, flexible, and shareable across different projects.

The bottom line is that all UI fragments can be termed components in Blazor.

Creating a component in Blazor

We will now discuss the following two methods for creating components in Blazor:

  • Using a single file
  • Using a code-behind file

Let’s examine both of them in detail in this section.

Using a single file

We will use a single file with the .cshtml extension to create our component. To create a component file, right-click on the Pages folder of your BlazorDemo project and select New File. Type in the filename as CompDemo.cshtml and press Enter to create the file.

Put the following lines of code inside this file:

@page "/singlepagecomp"

<h1>@PageTitle</h1>
<hr/>
<p>This component is created using a single .cshtml page.</p>

@functions {
string PageTitle = "Component Demo";
}

Both the HTML and the @functions section are defined in only one file, that is, CompDemo.cshtml. Here, we have defined a PageTitleproperty to set the title on the page. On execution, this page will show a heading and a sample message, as defined in this property. But before running this application, we need to add the navigation link to this page to the \Shared\NavMenu.cshtml file. Open the \Shared\NavMenu.cshtml file and add the following code to it:

<li class="nav-item px-3">
  <NavLink class="nav-link" href="singlepagecomp">
    <span class="oi oi-list-rich" aria-hidden="true"></span> Comp Demo
  </NavLink>
</li>

This will add a Comp Demo navigation menu item, which will redirect to the CompDemo.cshtml page when clicked.

Type the dotnet run command into the VS Code console and press Enter. Open the URL in the browser, and you should see a page similar to one shown in the following screenshot:

You can observe that we have a Comp Demo link in the navigation menu on the left. Click on it to navigate to the CompDemo.cshtml component. It should open a page like the one shown in the following screenshot:

You can observe that the route URL of the page has /singlepagecomp attached to it, and that the message is being displayed on the page as we defined it in our component.

Using a code-behind file

In this method, we will be using two files to create our component—one file to hold the HTML part of the component and another to hold the logic part of the component.

To add the files, we will follow the same process that we employed earlier. Right-click on the Pages folder and select New File. Name the file CodeBehindComp.cshtml and press Enter to create the file. This file will contain the HTML section of our component. Similarly, add one more file, CodeBehindComp.cshtml.cs, to the Pages folder. This file will contain our logic section, which will define the members of the component class.

Open CodeBehindComp.cshtml.cs and put the following code into it:

using Microsoft.AspNetCore.Blazor.Components;

namespace BlazorDemo.Pages
{
    public class CodeBehindCompModel : BlazorComponent
    {
        public string PageTitle { get; set; } = "Component Demo";
    }
}

Here, we have defined a CodeBehindCompModel class that contains a PageTitle string property, which sets the title of the component once it is rendered as a web page in the browser.

Note that the Blazor compiler generates classes for all of the view pages with the same name as the page name; hence, we have suffixed the class name with the word “model” to distinguish it from the page name. If we use the same class name as page name (CodeBehindComp, in this case), then it will result in a compile time error.

Open CodeBehindComp.cshtml and put the following code into it:

@page "/codebehindcomp"
@inherits CodeBehindCompModel

<h1>@PageTitle</h1>

<p>This component is created using two files,.cshtml and.cshtml.cs</p>

This page will inherit the class defined in our code-behind page by using the @inherits directive. This allows us to use all of the properties and methods defined in the class from this page.

Add the navigation link for this page, as defined in the following snippet, inside the \Shared\NavMenu.cshtml file:

<li class="nav-item px-3">
  <NavLink class="nav-link" href="codebehindcomp">
    <span class="oi oi-list-rich" aria-hidden="true"></span> Code Behind Comp
  </NavLink>
</li>

Execute the application by running the dotnet run command, and click on the Code Behind Comp link in the navigation menu on the left. You should see a page similar to the one shown in the following screenshot:

Here, the title of the page is set to Component Demo because of the PageTitle variable defined in the code-behind file, whereas the messages is displayed using the HTML defined in the .cshtml file.

Using a component within another component

The Blazor framework also allows us to use a component within another component. This will work like a parent-child relationship, where the parent component can refer to the child component.

We will demonstrate this concept with the help of an example.

Create two files in the Pages folder, and name them ParentComp.cshtml and ChildComp.cshtml.

Open the ChildComp.cshtml page and put the following code into it:

<hr/>
<h3> Welcome to the Child Component</h3>

@ChildContent
@functions { [Parameter] private RenderFragment ChildContent { get; set; } }

Here, we first defined some dummy messages to be displayed on the page. There is no route defined for this component, as it will act as a child component and will be referred to by another component. The parent component will pass the content to the child component so that it can be rendered in a <div> tag. We will use a RenderFragment property, ChildContent, to hold the message supplied by the parent component. ChildContent is a component parameter decorated by the [Parameter] attribute. RenderFragment is defined in the application metadata, and represents a segment of the UI content, implemented as a delegate that writes the content to an instance of Microsoft.AspNetCore.Blazor.RenderTree.RenderTreeBuilder.

The component parameter must fulfill the following two criteria:

  • It must be a non-public property
  • The component parameter that will receive the RenderFragment content must be named ChildContent

Open ParentComp.cshtml and enter the following code:

@page "/ParentComponent"

<h1>Parent-child example</h1>

<ChildComp>
    This is parent component data.
</ChildComp>

We defined the route of this application at the top of the preceding snippet as /ParentComponent. To refer to the child component, we use a tag with the same name as the file name of the child component, which is <ChildComp>in this case. The RenderFragment parameter is provided between the tags of the child component. In this case, we provide a string message that will be rendered by the child component.

Before executing the code, we need to add the following navigation link of the parent component to the \Shared\NavMenu.cshtml file:

<li class="nav-item px-3">
  <NavLink class="nav-link" href="ParentComponent">
    <span class="oi oi-list-rich" aria-hidden="true"></span> Parent-Child
  </NavLink>
</li>

Run the application and click on the Parent-Child link in the navigation menu. You should see a page similar to the following screenshot:

You can see the content of the parent component, along with that of the child component, displayed on the page.

If you found this article interesting, you can explore Blazor Quick Start Guide to work with the fundamentals of Blazor to create rich and interactive web application. Blazor Quick Start Guide introduces you to the core concepts of Blazor, and how to apply these to a real-world web app with the help of Entity Framework Core and SQL Server.

Understanding React Pure Components

Many people are confused by the difference between a Functional Component and a Pure Component. Most of them think that they are the same, but this is not true. When you use a React Pure Component, We need to import PureComponent from React:

    import React, { PureComponent } from 'react';

If your React component’s render method is “pure” (that means it renders the same result, given the same props and state), you can use this function to improve the performance of your application. A Pure Component performs a shallow comparison for the props and nextProps objects as well as the state and nextState objects. Pure components do not include the shouldComponentUpdate(nextProps, nextState) method, and if you try to add it, you’ll get a warning from React.

In this article, you’ll learn to create a basic example to understand how Pure Components works. To begin, you need to install the Chrome extension React Developer Tools to do a simple debug in your application. Download React Developer Tools from https://chrome.google.com/webstore/detail/react-developer-tools/fmkadmapgofadopljbjfkapdkoienihi.

Building your React application

First, create your React application using create-react-app. Once that is done, you can proceed to create your first React component.

Before you install create-react-app, remember that you need to download and install Node from www.nodejs.org. You can install it for Mac, Linux, and Windows.

Install create-react-app globally by typing this command in your Terminal:

  npm install -g create-react-app

Alternatively, you can use a shortcut:

  npm i -g create-react-app

Now build your first React application by following these steps:

  1. Create your React application with the following command:
create-react-app my-first-react-app
  1. Go to the new application with cd my-first-react-appand start it with npm start.
  2. The application should now be running at http://localhost:3000.
  3. Create a new file called js inside your src folder:
import React, { Component } from 'react';



class Home extends Component {

render() {

return <h1>I'm Home Component</h1>;

  }

}



export default Home;

File: src/Home.js

  1. You may have noticed that you are exporting your class component at the end of the file, but it’s fine to export it directly on the class declaration, like this:
import React, { Component } from 'react';

    export default class Home extends Component {

render() {

return<h1>I'm Home Component</h1>;

      }

    }

File: src/Home.js

  1. Now that you have created the first component, you need to render it. So, open the jsfile, import the Home component, and add it to the render method of the App component. If you are opening this file for the first time, you’ll probably see a code like this:
import React, { Component } from 'react';

import logo from './logo.svg';

import './App.css';

class App extends Component {

render() {

return (
 Welcome to React
);       
}     
}     
export default App;

To get started, edit src/App.js               and save to reload.

File: src/App.js

  1. Now change this code a bit. You need to import your Home component and then add it to the JSX. You also need to replace the <p> element with your component, like this:   
import React, { Component } from 'react';

import logo from './logo.svg';



// We import our Home component here...

import Home from './Home';

import './App.css';

class App extends Component {

render() {

return (

Welcome to React
{/* Here we add our Home component to be render it */}

);} } export default App;

File: src/components/App.js

  1. Now, create the Numbers component:
// Dependencies

import React, { Component } from 'react';
// Components
import Result from './Result';

// Styles

import './Numbers.css';



class Numbers extends Component {

state = {

numbers: '', // Here we will save the input value

results: [] // In this state we will save the results of the sums

};

handleNumberChange = e => {

const { target: { value } } = e;



// Converting the string value to array

// "12345" => ["1", "2", "3", "4", "5"]

const numbers = Array.from(value);

// Summing all numbers from the array

 // ["1", "2", "3", "4", "5"] => 15

const result = numbers.reduce((a, b) => Number(a) + Number(b), 0);



// Updating the local state

this.setState({

numbers: value,

results: [...this.state.results, result]

});
}

render() {
return (
  {/* Rendering the results array */}
              {this.state.results.map((result, i) => (                               ))}

)       }     }   export default Numbers;

File: src/components/Numbers/Numbers.js

  1. Then, create the Result component (as a Class Component):
import React, { Component } from 'react';



class Result extends Component {

render() {

return<li>{this.props.result}</li>;

      }

    }



 export default Result;

File: src/components/Numbers/Result.js

  1. Finally, create the styles:
.Numbers {

      padding: 30px;

    }

.Numbers input[type=number]::-webkit-inner-spin-button,

    .Numbers input[type=number]::-webkit-outer-spin-button {

      -webkit-appearance: none;

      margin: 0;

    }



 .Numbers input {

      width: 500px;

      height: 60px;

      font-size: 20px;

      outline: none;

      border: 1px solid #ccc;

      padding: 10px;

    }



.Numbers ul {

      margin: 0 auto;

      padding: 0;

      list-style: none;

      width: 522px;

    }



 .Numbers ul li {

      border-top: 1px solid #ccc;

      border-left: 1px solid #ccc;

      border-right: 1px solid #ccc;

      padding: 10px;

    }



.Numbers ul li:first-child {

      border-top: none;

    }



.Numbers ul li:last-child {

      border-bottom: 1px solid #ccc;

    }

File: src/components/Numbers/Numbers.css

How React Pure Component works…

If you run the application, you will see this:

  1. You have used an input with the number type, which means you’ll only accept numbers if you start writing numbers (1, then 2, then 3, and such). You will see the results of the sum on each row (0 + 1 = 1, 1 + 2 = 3, 3 + 3 = 6):

Now, inspect the application using React Developer Tools. You need to enable the Highlight Updates option:

After this, start writing multiple numbers in the input (quickly), and you will see all the renders that React is performing:

As you can see, React is doing a lot of renderings. When the highlights are red, it means the performance of that component is not good. Here’s when React Pure Components will help you. Migrate your Result component to be a Pure Component:

import React, { PureComponent } from 'react';



class Result extendsPureComponent {

render() {

return <li>{this.props.result}</li>;

      }

    }



   export default Result;

File: src/components/Numbers/Result.js

Now if you try to do the same with the numbers, see the difference:

With the Pure Component React, you do less renders in comparison to a Class Component. Probably, you may now think that if you use a Stateless component instead of a Pure Component, the result will be the same. Unfortunately, this won’t happen. If you want to verify this, change the Result component again and convert it into a Functional Component.:

import React from 'react';



const Result = props => <li>{props.result}</li>;



 export default Result;

File: src/components/Numbers/Result.js

See what happens with the renders:

As you can see, the result is the same as the Class Component. This means that using a Stateless Component will not help you improve the performance of your application all the time. If you have components that you consider are pure, consider converting them into Pure components.

If you found this article interesting, you can explore Carlos Santana Roldan’s React Cookbook to be on the road to becoming a React expert. React Cookbook has over 66 hands-on recipes that cover UI development, animations, component architecture, routing, databases, testing, and debugging with React.

Using Modules in Node.js

Node.js is an event-driven, server-side JavaScript environment. Node.js runs JS using the V8 engine developed by Google for use in their Chrome web browser. Leveraging V8 allows Node.js to provide a server-side runtime environment that compiles and executes JS at lightning speeds.

The Module System

This article covers the Node’s module system and the different categories of the Node.js modules.

Application Modularization

Like most programming languages, Node.js uses modules as a way of organizing code. The module system allows you to organize your code, hide information, and only expose the public interface of a component using module.exports.

Node.js uses the CommonJS specification for its module system:

  • Each file is its own module, for instance, in the following example, jsand math.js are both modules
  • Each file has access to the current module definition using the modulevariable
  • The export of the current module is determined by the module.exportsvariable
  • To import a module, use the globally available requirefunction

Take a look at a simple example:

// math.js file

function add(a, b)

{

  return a + b;

}

…

…

module.exports =

{

  add,

  mul,

  div,

};

// index.js file

const math = require('./math');

console.log(math.add(30, 20)); // 50

To call other functions such as mul and div, use object destructuring as an alternative when requiring the module, for example, const { add } = require(‘./math’);. The code files for the section The Module System are placed at Code/Lesson-1/b-module-system.

Module Categories

You can place Node.js modules into three categories:

  • Built-in (native) modules: These are modules that come with Node.js itself; you don’t have to install them separately.
  • Third-party modules: These are modules that are often installed from a package repository. npm is a commonly used package repository, but you can still host packages on GitHub, your own private server, and so on.
  • Local modules: These are modules that you have created within your application, like the example given previously.

Built-In Modules

These are modules that can be used straight away without any further installation. All you need to do is to require them. There are quite a lot of them, but here are a few that you are likely to come across when building web applications:

  • assert: Provides a set of assertion tests to be used during unit testing
  • buffer: To handle binary data
  • child_process: To run a child process
  • crypto: To handle OpenSSL cryptographic functions
  • dns: To do DNS lookups and name resolution functions
  • events: To handle events
  • fs: To handle the filesystem
  • httpor https: For creating HTTP(s) servers
  • stream: To handle streaming data
  • util: To access utility functions like deprecate (for marking functions as deprecated), format (for string formatting), inspect (for object debugging), and so on

For example, the following code reads the content of the lesson-1/temp/sample.txt file using the in-built fs module:

const fs = require('fs');

let file = `${__dirname}/temp/sample.txt`;

fs.readFile(file, 'utf8', (err, data) =>

{

  if (err) throw err;

  console.log(data);

});

npm – Third-Party Module Registry

Node Package Manager (npm) is the package manager for JavaScript and the world’s largest software registry, enabling developers to discover packages of reusable code. To install an npm package, you only need to run the npm install <package-name> command within your project directory.

Here’s a simple example. If you want to use a package (library) like request in your project, you can run the following command on your Terminal, within your project directory:

npm install request

To use it in your code, you should require it, like any other module:

const request = require('request');

request('http://www.example.com', (error, response, body) =>

{

  if (error) console.log('error:', error); // Print the error if one occurred

  else console.log('body:', body); // Print the HTML for the site.

});

More details about npm can be found at https://docs.npmjs.com/. When you run the npm install <module-name> command on your project for the first time, the node_modules folder gets created at the root of your project.

Scanning for node_modules

It’s worth noting how Node.js goes about resolving a particular required module. For example, if a /home/tony/projects/foo.js file has a require call require(‘bar’), Node.js scans the filesystem for node_modules in the following order. The first bar.js that is found is returned as follows:

  • /home/tony/projects/node_modules/bar.js
  • /home/tony/node_modules/bar.js
  • /home/node_module/bar.js
  • /node_modules/bar.js

Node.js looks for node_moduels/bar in the current folder followed by every parent folder until it reaches the root of the filesystem tree for the current file. Note that the module foo/index.js can be required as foo, without specifying an index and will be picked by default.

Handy npm Commands

Now dive a little deeper into npm, by looking at some of the handy npm commands that you will often need:

  • npm init: Initializes a Node.js project. This should be run at the root of your project and will create a respective jsonfile. This file usually has the following parts (keys):
  • name: Name of the project.
  • version: Version of the project.
  • description: Project description.
  • main: The entry-point to your project, the main file.
  • scripts: This will be a list of other keys whose values will be the scripts to be run, for example, test, dev-server. Therefore, to run this script, you will only need to type commands such as npm run dev-server, npm run test, and so on.
  • dependencies: List of third-party packages and their versions used by the project. Whenever you do npm install <package-name> –save, this list is automatically updated.
  • devDependencies: List of third-party packages that are not required for production, but only during development. This will usually include packages that help to automate your development workflow, for example, task runners like gulp.js. This list is automatically updated whenever you do npm install <package-name> –save-dev.
  • npm install: This will install all the packages, as specified in the jsonfile.
  • npm install <package-name> <options>:
  • The –saveoption installs the package and saves the details in the json file.
  • The –save-devoption installs the package and saves the details in the json, under devDependencies.
  • The –globaloption installs the package globally in the whole system, not only in the current system. Due to permissions, this might require running the command with administrator rights, for example, sudo npm install <package-name> –global.
  • npm install <package-name>@<version>, installs a specific version of a package. Usually, if a version is not specified, the latest version will be installed.
  • npm list: Lists the packages that have been installed for the project, reading from what is installed in node_modules.
  • npm uninstall <package-name>: Removes an installed package.
  • npm outdated: Lists installed packages that are outdated, that is, newer versions have been released.

Local Modules

You have already looked at how local modules are loaded from the previous example that had math.js and index.js.

Since JavaScript Object Notation (JSON) is such an important part of the web, Node.js has fully embraced it as a data format, even locally. You can load a JSON object from the local filesystem the same way you load a JavaScript module. During the module loading sequence, whenever a file.js is not found, Node.js looks for a file.json.

See the example files in lesson-1/b-module-system/1-basics/load-json.js:

const config = require('./config/sample');

console.log(config.foo); // bar

Here, you will notice that once required, the JSON file is transformed into a JavaScript object implicitly. Other languages will have you read the file and perhaps use a different mechanism to convert the content into a data structure such as a map, a dictionary, and so on.

For local files, the extension is optional, but should there be a conflict, it might be necessary to specify the extension. If you have both a sample.js and a sample.json file in the same folder, the .js file will be picked by default; it would be prudent to specify the extension, for example const config = require(‘./config/sample.json’).

When you run npm install, without specifying the module to install, npm will install the list of packages specified (under dependencies and devDependencies in the package.json file in your project). If package.json does not exist, it will give an error indicating that no such file has been found.

Activity: Running Basic Node.js Code

Open the IDE and the Terminal to implement this solution and learn how to write a basic Node.js file and run it. Write a very basic mathematical library with handy mathematical functions using the following steps:

  1. Create your project directory (folder), where all the code for this will be kept. Inside this directory, create another directory named lesson-1, and inside it, create another directory called activity-a. All this can be done using the following command:
mkdir -p beginning-nodejs/lesson-1/activity-a
  1. Inside activity-a, create a file using the touch maths.js
  2. Inside this file, create the following functions:
  • add: This takes any two numbers and returns the sum of both, for example, add(2, 5)returns 7
  • sum: Unlike add, sum takes any number of numbers and returns their sum, for example, sum(10, 5, 6)returns 21
  1. After these functions, write the following code to act as tests for your code:
console.log(add(10, 6)); // 16

console.log(sum(10, 5, 6)); // 21
  1. Now, on the Terminal, change directory to lesson-1.
  2. To run the code, run the following command:
node activity-a/math.js

The 16 and 21 values should be printed out on the Terminal.

Activity: Using a Third-Party Package

This activity will build upon the, Running Basic Node.js activity. If the argument is a single array, sum up the numbers, and if it’s more than one array, first combine the arrays into one before summing up. Use the concat() function from lodash, which is a third-party package that you need to install.

Now create a new function, sumArray, which can sum up numbers from one or more arrays using the following steps:

  1. Inside Lesson-1, create another folder called activity-b.
  2. On the Terminal, change directory to activity-band run the following command:
npm init
  1. This will take you to an interactive prompt; just press Enter all the way, leaving the answers as suggested defaults. The aim here is to get a json file, which will help organize your installed packages.
  2. Since you’ll be using lodash, install it. Run the following command:
npm install lodash--save

Notice that you’re adding the –save option on your command so that the package installed can be tracked in package.json. When you open the package.json file created in step 3, you will see an added dependencies key with the details.

  1. Create a jsfile in the activity-b directory and copy the math.js code from ActivityRunning Basic Node.js into this file.
  2. Now, add the sumArrayfunction right after the sum
  3. Start with requiring lodash, which you installed in step 4 since you’re going to use it in the sumArrayfunction:
const _ = require('lodash');
  1. The sumArrayfunction should call the sum function to reuse your code. Use the spread operator on the array. See the following code:
function sumArray()

{

  let arr = arguments[0];

  if (arguments.length > 1)

  {

    arr = _.concat(...arguments);

  }

  // reusing the sum function

  // using the spread operator (...) since

  // sum takes an argument of numbers

  return sum(...arr);

}
  1. At the end of the file, export the three functions, add, sum, and sumArraywith exports.
  2. In the same activity-bfolder, create a file, js.
  3. In jsfile, require ./math.js and go ahead to use sumArray:
// testing

console.log(math.sumArray([10, 5, 6])); // 21

console.log(math.sumArray([10, 5], [5, 6], [1, 3])) // 30
  1. Run the following code on the Terminal:
node index.js

You should see 21 and 30 printed out.

If you found this article interesting, you can explore Anthony Nandaa’s Beginning API Development with Node.js to learn everything you need to get up and running with cutting-edge API development using JavaScript and Node.js. Beginning API Development with Node.js begins with the basics of Node.js in the context of backend development and quickly leads you through the creation of an example client that pairs up with a fully authenticated API implementation.