Categories
javascript reactjs

React.js – Understanding JSX

Hey guys 👋🏻,
In this post, let us learn what JSX is in React and why it is important for us as React developers to understand it.

Image description

In this post, let us understand

✔ What is JSX ?
✔ Example of JSX
✔ JSX code being equivalent to React.createElement calls.
✔ JSX Restrictions

What is JSX ?

JSX is a syntax extension to JavaScript. It is used to write HTMLish code in JavaScript files which later gets transpiled to normal JavaScript by our development workflow.

Example of JSX

Image description

In the above example, you can see we are returning HTMLish kind of code from our component function. personName is a variable that we are interpolating right inside the template of our component. This in the end gets transpiled to JavaScript.

Before Transpilation

Image description

After Transpilation

Image description

JSX code is nothing but multiple calls to the React.createElement method to build up the HTML for our component.

JSX Restrictions

  1. It allows us to write HTMLish code that we write in JavaScript files.
  2. It enforces restrictions on some keywords that we cannot use like classfor etc that are reserved keywords in JavaScript. We have equivalents for them though.
  3. JSX expression must have exactly one root element and it is under this root element that you nest your JSX code.

So this is it for this article. Thanks for reading.
Don’t forget to leave a like if you loved the article. Also share it with your friends and colleagues.

Alt Text

Categories
javascript reactjs

A Brief Introduction to React.js

Hey everyone 👋🏻,

In this article, let us cover a brief introduction to React.js

Introduction

Image description

React is an open source, front-end JavaScript Library for building modern sleek user interfaces.

It is maintained by Facebook. It is used to create SPAs.

Why React ?

  1. Uses component based architecture to structure your application.
  2. Allows you to write reusable components that can be used across different applications
  3. Easy to learn
  4. Ensures stable code.

Features of React

  1. Optimization of code using a complex development workflow already done for us.
  2. Writing HTMLish Code in JavaScript files using JSX.
  3. Faster rendering because of Virtual DOM.

Disadvantages of React

Not a complete framework
Compared to Angular which is like a kitchen of tools that has everything built in, React depends on a lot of other external libraries that glue with it for creating modern frontends.

So this is it for this article. Thanks for reading.
Don’t forget to leave a like if you loved the article. Also share it with your friends and colleagues.

Alt Text

The credits for the vectors used in above articles goes to Vecteezy :
Web Developer Vectors by Vecteezy

Categories
javascript

Understanding Promise.all, Promise.race and Promise.allSettled

Hey everyone 👋🏻,

In this article, let us discuss some very important methods that we have in the Promise API – Promise.all,Promise.allSettledPromise.race.
So let’s start with Promise.all

Promise.all

The Promise.all() method takes an iterable of promises as an input, and returns a single Promise that resolves to an array of the results of the input promises. This returned promise will resolve when all of the input’s promises have resolved, or if the input iterable contains no promises. It rejects immediately upon any of the input promises rejecting or non-promises throwing an error, and will reject with this first rejection message / error.

Alt Text

Promise.allSettled

The Promise.allSettled() method returns a promise that resolves after all of the given promises have either fulfilled or rejected, with an array of objects that each describes the outcome of each promise.

It is typically used when you have multiple asynchronous tasks that are not dependent on one another to complete successfully, or you’d always like to know the result of each promise.

In comparison, the Promise returned by Promise.all() may be more appropriate if the tasks are dependent on each other / if you’d like to immediately reject upon any of them rejecting.

Alt Text

Promise.race

The Promise.race() method returns a promise that fulfills or rejects as soon as one of the promises in an iterable fulfills or rejects, with the value or reason from that promise.

Alt Text

So this is it for this article, I do have a video that covers the same with a lot of interesting examples, so feel free to check that :

So this was it for this one.

Thanks for reading !

Categories
javascript

React Hooks : Demystifying the useEffect Hook in under 15 minutes [ examples + video ]

Hey everyone 👋🏻,

In this article, let us understand about the useEffect React Hook in under 15 minutes.

Example 1: Counter Example for useEffect

CODE :

import { useState, useEffect} from "react"; 

const Effect = props => { 
  const [counter, setCounter] = useState(0);
  useEffect(() => { 
    console.log('In Effect.js, [AFTER RENDER]');
  }); 
  return ( 
    <div>
      <button onClick={() => setCounter(prevCounter => prevCounter + 1)}>Increment Counter</button>
      <h1>Current Value : {counter}</h1>
      <button onClick={() => setCounter(prevCounter => prevCounter - 1)}>Decrement Counter</button>
    </div>
  )
}

export default Effect; 


Example 2: API Call Side Effect example (useEffect)

import { useState, useEffect } from "react"; 

const APICallEffect = props => { 
  const [todo, setTodo] = useState(null); 
  const [id, setId] = useState(1); 
  const fetchTodo = (id) => { 
    return fetch('https://jsonplaceholder.typicode.com/todos/' + id)
    .then(response => response.json()); 
  }
  useEffect(() => { 
    console.log('Effect ran...');
    fetchTodo(id)
     .then(setTodo); 
  },[id]);

  const incrementId = () => setId(prevId => prevId + 1); 

  if(todo === null) return <h1>Loading...</h1>
  return ( 
     <div>
        <h1>id : {id}, todo : {todo.title}</h1>
        <button onClick={incrementId}>incrementId</button>
     </div>
  )
}
export default APICallEffect;

Example 3: useEffect with cleanup

import { useState, useEffect, Fragment  } from "react"; 

const EffectWithCleanup = props => { 
  const[xCoordinate, setXCoordinate] = useState(0); 
  const[yCoordinate, setYCoordinate] = useState(0); 
  const handleCoordinateUpdate = event => { 
    console.log(event.clientX, event.clientY); 
    setXCoordinate(event.clientX); 
    setYCoordinate(event.clientY); 
  }

  useEffect(() => { 
    console.log('useEffect ran...'); 
    window.addEventListener('mousemove', handleCoordinateUpdate); 
    return () => {
      console.log('cleanup....');
      window.removeEventListener('mousemove',handleCoordinateUpdate);
    }
  },[]);
  return ( 
    <Fragment> 
      <div>
      <h1>X coordinate: {xCoordinate}</h1>
      <h1>Y coordinate: {yCoordinate} </h1>
      </div>
    </Fragment>
  )
}
export default EffectWithCleanup;

Video 📹

So this was it for this one.

Thanks for reading !

Categories
javascript

Beginner JavaScript – 14 – Creating and Inserting Elements to the DOM

✨Beginner JavaScript – 14 – Creating and Inserting Elements to the DOM

Hey everyone 👋🏻,

In this article, let us discuss about Creating, Inserting and Removing Elements from the DOM in JavaScript. This is the fourteenth part of my Beginner JavaScript Series on Dev.

Let us first discuss about creating and inserting elements in DOM before we move our attention to removing elements.

Creating and Inserting Elements in DOM

For creating and inserting elements in DOM, I would live to cover basically two ways :

1. HTML Strings – innerHTML, insertAdjacentHTML

2. document.createElement – appendChild, append

Let us first talk about HTML Strings :

HTML Strings

innerHTML

The innerHTML property sets or returns the HTML content (inner HTML) of an element.

// Let us assume we want to add some html markup inside some element with the id of x12
const markup = `<div>
  <h1>This is some dummy markup </h1>
</div>
`;
document.getElementById("x12").innerHTML = markup;

insertAdjacentHTML

The insertAdjacentHTML() method parses (goes over) the given HTML code and inserts the specified nodes that we create into the DOM tree at a specified position. The benefit of using insertAdjacentHTML is that it does not reparse the element it is being used on, so it saves the cost of re-initiating this step and thus it avoids the extra step of serialization, making it much faster than direct innerHTML manipulation.

SYNTAX

element.insertAdjacentHTML(position, text);
// Let us assume we want to add some html markup inside some element with // the id of x12
const markup = `<div>
  <h1>This is some dummy markup </h1>
</div>
`;
document.getElementById("x12").innerHTML = markup;

document.createElement – appendChild and append methods

The document.createElement() method is used to create a new HTML element and attach it to a DOM tree.

Let us see the syntax for creating an element using the document.createElement method.

SYNTAX TO CREATE AN ELEMENT OF A PARTICULAR TYPE :

const element = document.createElement(elementType); 

Let us see the examples for appendChild and append methods.

Let us say our starter HTML is this :

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>append and appendChild methods</title>
</head>
<body>

</body>
</html>

Let us create a div element using the document.createElement method and then make use of the appendChild method to add the newly created div to the body of the HTML.

const div = document.createElement('div'); 
div.innerHTML = '<p>This is a div element</p>';
// Append the div as a child element to the body element. 
document.body.appendChild(div);

So this is it for this article. Let us learn about how we can remove elements from the DOM in the next article.

Thanks for reading !

Categories
javascript

Beginner JavaScript – 13 – Understanding DOM Traversal

✨Beginner JavaScript – 13 – Understanding DOM Traversal

Hey everyone 👋🏻,

In this article, let us cover a detailed introduction on Document Object Model (DOM) in JavaScript. This is the thirteenth part of my Beginner JavaScript Series on Dev.

DOM Traversal – A complete picture

In DOM Traversal, a concept of Node Relationships comes into picture. So let us understand this in great depth first. But before that we need to understand one thing :

Alt Text

“” Everything in an HTML Document is considered as a Node. “”

The nodes that are present in the DOM Tree possess a hierarchical relationship to each other.
There are certain terms that we can use to describe or give a name to these relationships – like parentchildsibling.

Now there are a couple of things that you need to commit to the mind :

Alt Text

  1. The first and foremost thing that you need to remember is that in a DOM tree that gets generated, the top node is called as the root node of the tree.
  2. Every node has exactly one parent, except the root node which has no parent.
  3. The terms parent, child, and sibling are used to describe the relationships.
  4. A node can have any number of children
  5. Sibling nodes are those nodes that have the same parent.

Traversing up the DOM Tree, along a Level and down the DOM Tree

Alt Text

The properties that are used for DOM Traversal are demonstrated in my video Exercise : DOM Traversal along levels, here is the link for the video if you want to check it out.

So this is it for this one. I do have videos for these so if you like to watch instead of reading, definitely check them out.

Thanks for reading !

👉🏻 Follow me on Twitter : https://twitter.com/The_Nerdy_Dev

👉🏻 Check out my YouTube Channel : https://youtube.com/thenerdydev

Categories
javascript

Beginner JavaScript – 12 – Accessing and Manipulating DOM Elements (video)

✨Beginner JavaScript – 12- Accessing and Manipulating DOM Elements ( video )

Hey everyone 👋🏻,

In this video, let us cover a detailed introduction on Accessing and Manipulating DOM Elements in JavaScript. This is the twelfth part of my Beginner JavaScript Series.

 

So this is it for this one. I do have a video on Introduction to Document Object Model and Query Selection as well. So make sure to check them out if that interests you :

Thanks for reading !

👉🏻 Follow me on Twitter : https://twitter.com/The_Nerdy_Dev

👉🏻 Check out my YouTube Channel : https://youtube.com/thenerdydev

Categories
javascript

Beginner JavaScript – 11 – Document Object Model & Query Selection

✨Beginner JavaScript – 11- Document Object Model & Query Selection

Hey everyone 👋🏻,

In this article, let us cover a detailed introduction on Document Object Model (DOM) in JavaScript. This is the eleventh part of my Beginner JavaScript Series.

Document Object Model – A complete picture  

Alt Text

Alt Text

Alt Text

Document Object Model, or DOM for short is a programming API for HTML and XML documents. It defines the logical structure of documents and the way a document is accessed and manipulated. So in essence, it is a visual representation of a hierarchical structure of all of the objects and properties that are contained in a web document.

Let’s dive a bit DEEPER

To understand the big picture of the Document Object Model. We need to understand that when our browser first loads an HTML page, it first maps it to a visual representation. So it basically parses over the HTML code that you and I write, creates a visual hierarchical representation of it which is called as the DOM. Each element that we define in our HTML template maps to some DOM object that is part of this DOM structure that we are talking about.
So the HTML DOM that gets produced by the browser, constructs a tree-like structure that consists of all your HTML page element as DOM objects.
For instance, assume that the below HTML code gets loaded in the browser.

<!DOCTYPE html>
<html>
    <head>
        <title>This is some HTML page</title>
    </head>
    <body>
        <p class="element-one">I am a paragraph</p>
        <h1>I am an important element </h1>
    </body>
</html>

Querying Elements in DOM

Querying for Elements in the DOM can be used using DOM Selectors. So let us understand 5 ways using which you can select elements in a DOM using selectors.

1. getElementsByTagName

The getElementsByTagName method returns us an HTMLCollection of elements with the given tag name. Here the complete document is searched, including the root node until we find all the elements that contain a certain tag name that is passed to this method as an argument. The interesting thing about using the getElementsByTagName method is that the returned HTMLCollection is live, meaning that it updates itself automatically to stay in sync with the DOM tree without having to call the same method again.

// As an example, let us say we are looking for all the h1 elements
const elements = document.getElementsByTagName('h1'); 

2. getElementsByClassName

The getElementsByClassName method returns a live HTMLCollection of elements which have a particular class on them that we are looking for. When called on the document object, the complete document is searched, including the root node.

// As an example, let us say we are looking for an element with the class of game
const games = document.getElementsByClassName('game'); 

3. getElementById

The getElementById returns an element object whose id attribute matches with the id that we are looking. Since element IDs, as we know, are required to be unique if specified, they’re a useful way to get access to a specific element quickly.

// As an example, let us say we are looking for an element with id of username. Each HTML page can only have one such element that has the id that we are looking for. 
const username = document.getElementById('username'); 

4. querySelector

The querySelector returns us the first element within the document that matches the specified selector, or group of selectors. If no matches are found, null is returned.

// As an example, let us say we are looking for an element with id of username. Each HTML page can only have one such element that has the id that we are looking for. 
const username = document.querySelector('#username'); 

5. querySelectorAll

The querySelectorAll method returns a static, NOT live NodeList representing a list of all the elements that we have in the document that match the specified group of selectors.

// As an example, let us say we are looking all elements that have the class of user on it.
const users = document.querySelectorAll('.user'); // Static Non-Live Node List

So this is it for this one. I do have a video on Introduction to Document Object Model and Query Selection as well. So make sure to check them out if that interests you :

Thanks for reading !

👉🏻 Follow me on Twitter : https://twitter.com/The_Nerdy_Dev

👉🏻 Check out my YouTube Channel : https://youtube.com/thenerdydev

Categories
javascript

Beginner JavaScript – 10 – Immediate Invoked Function Expressions

✨Beginner JavaScript – 10  -Immediately Invoked Function Expressions

Hey everyone 👋🏻,

In this article, let us discuss about Immediate Invoked Function Expressions (IIFEs) in JavaScript. This is the tenth part of my Beginner JavaScript Series on Dev.

Immediately Invoked Function Expressions – A complete picture

Alt Text

Immediately Invoked Function Expression, or IIFE for short is a function that is executed immediately after it’s created.
A key point to note here is that it has nothing to do with any event-handler for any events (such as window.onload etc.)

It has nothing to do with any event-handler for any events (such as document.onload).

// Syntax (arguments are optional)
(function(argument_one, argument_two,...){
  // code goes inside here (function body) 
})(value_one, value_two, ...);

Consider the part within the first pair of parentheses: (function(){})(); this is what is called as a regular function expression. Also if you observe the syntax carefully in the end we have an invocation parenthesis to invoke the function.

Now the thing you need to understand here is that this pattern is often used when trying to avoid polluting the global namespace, because all the variables used inside the IIFE (like in any other normal function) are not visible outside its scope.

(function(){
  // all your code here
  const foobar = function() {};
  window.onload = foobar;
  // ...
})();
// foobar is unreachable here (it’s undefined)

In the case of IIFEs, the function is executed right after it’s created, not after it is parsed. The entire script block is parsed before any code in it is executed. Also, parsing code doesn’t automatically mean that it’s executed, if for example the IIFE is inside a function then it won’t be executed until the function is gets invoked.

So this is it for this one. I do have a video on IIFEs as well. So make sure to check that if interests you :

Thanks for reading !

👉🏻 Follow me on Twitter : https://twitter.com/The_Nerdy_Dev

👉🏻 Check out my YouTube Channel : https://youtube.com/thenerdydev

Categories
javascript

Beginner JavaScript – 9 – Functions and Different Ways of Declaring them

✨Beginner JavaScript – 9 -Functions and Different Ways of Declaring them

Hey everyone 👋🏻,

In this article, let us discuss about the Functions in JavaScript. This is the ninth part of my Beginner JavaScript Series.

Functions in JavaScript – A Complete Picture

Functions in JavaScript are one of the most fundamental building blocks that you will often find being used heavily in all the codebases that you work with.

 A function is kind of similar to a procedure, so you basically define a procedure similar to what we have for preparing a recipe or something like that. The job of a function is to perform a task for which we define a set of statements inside the body of the function and all that happens on the execution of the function is the execution of those statements line by line to do some work and optionally return a value. 

Now for a procedure to serve the role of a function, it should take some input as arguments and return an output where there is some obvious relationship between the input and the output.
To use a function, as a first step we need to define it.

function <name_of_function>(argument_one, argument_two,...) { 
   // here goes the body of the function 
}

Then to invoke it we just have to say:

<name_of_function>(argument_one, argument_two,...)

Note: The invocation parenthesis is a must after the name of the function in order to call it.

So now we know the syntax for declaring a function. Let us see an example of a simple function to multiply two numbers and then see how we can invoke it.

function multiplyTwoNumbers(numberOne, numberTwo) { 
 // Name of the function - multiplyTwoNumbers 
 // Arguments : numberOne, numberTwo 
 const product = numberOne * numberTwo;  
 return product; 
} 

// Now in order to call it we need to make use of the invocation parenthesis and store the returned result in a variable. 
// Let's name it as result. 
const result = multiplyTwoNumbers(2,3);
console.log(result);  // logs 6 to the console. 

Different Ways of Declaring Functions

1. Function Declarations

2. Function Expressions

3. Arrow Functions

Let us first talk about Function Declarations.

Function Declarations

A function definition (also called a function declaration, or function statement) consists of the function keyword, followed by:1. The name of the function.

2. A list of parameters to the function, enclosed in parentheses and separated by commas.

3. The body of the function that is enclosed in the curly braces.

Check the multiplyTwoNumbers function for example.

Function Expressions

A function expression is very similar to and has almost the same syntax as a function declaration. But there is a slight difference in the syntax as well. Let us understand the syntax.

const <name_of_function> = function (argument_one, argument_two,...) { 
 // body of the function 
} 
// To invoke the function, it is dead simple, all you have to do // is to use the invocation parenthesis to call it. 
<name_of_function>(); 

But…🤔 what is the difference between function declarations and function expressions, then ?

The difference lies in how the browser loads them into the execution context.

Function declarations get loaded before any code gets executed. They are always hoisted at the top of the file.

Function expressions load only when the interpreter reaches that line of code where they are declared.

So if you try to call a function expression before it’s loaded, you’ll get an error! If you call a function declaration instead, it’ll always work, because no code can be called until all declarations are loaded.

Let us see an example for it :

// Example for Function Expressions 

console.log(add(3,4)); // ERROR! add wasn't loaded yet
var add = function(numberOne, numberTwo) { 
      return numberOne + numberTwo; 
} 

// Example for Function Declarations

console.log(add_2(3,4)); // logs 7 (declarations are loaded first before execution happens)
function add_2(numberOne, numberTwo) { 
     return numberOne + numberTwo; 
}  

Arrow Functions

Arrow functions in ES2015 provide a more concise syntax but it is more or less the same as a function expression.

An arrow function expression is an anonymous function expression written with the “fat arrow” syntax ( => ). Like traditional function expressions, arrow functions are not hoisted, and so you cannot call them before you declare them.

const <name_of_function> = (argument_one, argument_two,...) => { 
 // body of the function 
} 
// To invoke the function, it is dead simple, all you have to do // is to use the invocation parenthesis to call it. 
<name_of_function>(); 

We will learn more about arrow functions in a later post.
So this is it for this one.

Check these videos where I cover everything pertaining to this article with more examples.

Thanks for reading !

👉🏻 Follow me on Twitter : https://twitter.com/The_Nerdy_Dev

👉🏻 Check out my YouTube Channel : https://youtube.com/thenerdydev