Categories
javascript vuejs

Vue.js – Introduction

Hey guys 👋🏻,
In this post, I will be starting with a new series and it is on Vue.js. So in this first post, let us talk cover the Introduction to Vue.js

For this post we will first understand Props
✔ What is Vue.js ?
✔ How to Get Started ?
✔ Declarative Rendering

What is Vue.js?

Vue.js is a progressive JavaScript Frontend Framework for building modern, sleek and performant user interfaces. It is a very popular framework for building frontend applications just like Angular and React.js

How to get started ?

You can use Vue.js for building small widgets for your multi-page applications. For this you just need the CDN. For more complex applications, use the Vue CLI

Declarative Rendering

Vue.js provides a reactivity system that allows us to render content in a declarative manner right within the template using the mustache {{}} syntax.

Let us define the script where we house all our business logic for the component.

So this was all for the introduction. This is how we can create a basic Vue.js 3 application. We made the app reactive by connecting the data and the DOM.

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

React.js – Demystifying Virtual DOM

Hey guys 👋🏻,
In this post, let us talk about Virtual DOM in React.js.

For this post we will understand Virtual DOM
✔ What is Virtual DOM ?
✔ Why we need Virtual DOM ?
✔ Why Virtual DOM is faster and more efficient than real DOM ?

Image description

Why Virtual DOM ?

The DOM as we know represents the UI of your application. Every time there is a change in the state of your application UI, the DOM gets updated to represent that change. But the problem is that frequently manipulating the DOM affects performance, making it DEAD slow !

When changes are made to some element, the updated element and it’s children have to be re-rendered to update the application UI. The re-rendering of the UI is what makes it slow.

✔ More the UI components you have, more expensive will be the patches to the DOM as they would need to be re-rendered for every DOM update

👉🏻 Hence the need for Virtual DOM in React.

Now coming to question, what the heck is Virtual DOM 🤔?

The Virtual DOM is only a virtual representation of the DOM. Every time the state of our application changes, the virtual DOM gets updated instead of the real DOM.

Virtual DOM is faster and more efficient ..

Image description

When new elements are added to the UI, a virtual DOM is created which is a tree like representation. Each element is a node on this tree. If the state of any of any of these elements changes, a new virtual DOM tree is created. This tree is then compared or “diffed” with the previous virtual DOM tree.

Once this is done, the virtual DOM calculates the best possible method to make these changes to the real DOM. This ensures that there are minimal operations on the real DOM. Hence, reducing the performance cost of updating the real DOM. This updated tree is then batch updated to the real DOM.

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

React.js – What is Props ?

Hey guys 👋🏻,
In this post, let us cover what actually are props in React.js

For this post we will first understand Props
✔ What is Props ?
✔ Understanding Props
✔ Accessing Props in Functional and Class based Components
✔ Examples of Props

Image description

Introduction to Props

Props are used to make components configurabledynamic and flexible. Every HTML element as we know has some attributes like input element has valueplaceholder etc. It is dynamic content that you can configure from outside.

Understanding Props

Our components which are customized HTML elements can also be passed some arguments in form of attributes known as props so as to configure just like any other HTML element is configured and it is the parent component that passes these arguments to the child component.

Every child component receives props as an argument that is passed to it by React which is an object that holds the arguments that the parent component passed to the child component and that object is known as propsprops basically means all the properties that a component is receiving from outside.

When using functional components, you can access the props using the below syntax :

props.<propName>

When using class components, you can access the props using the syntax :

this.props.<propName>

EXAMPLES

Passing a prop of brand to the Computer component :

Image description

Defining our Computer component which receives the brand prop.

Image description

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

React.js – What is State ?

Hey guys 👋🏻,
In this post, let us cover an introduction to State in React.js.

For this post we will understand
✔What is State in React ?
✔ Example for creating State in React.
✔ Accessing the State
✔ Using setState and understanding its pitfall.
✔ Using setState with callback to resolve the pitfall.

Image description

Introduction to State

Every component manages its own state. With the introduction of React Hooks, you can also use state in functional components. But in this article, we will discuss about state in class components.

Example for creating state :

We define a state property inside the constructor function.

Image description

To access the state

To access the counter property defined in the state, we can access it in our JSX template by saying
this.state.counter

Image description

DON’T MUTATE THE STATE DIRECTLY, use setState

Image description

But there can be a problem, consider this …

Image description

setState does not always immediately update the component. It may batch or defer the update until later. Both the setState calls are enqueued when the value of counter is 0 thus causing the problem.

Let’s solve the above problem.

Image description

Use setState with callback because it is guaranteed to fire after the update has been applied. So first counter gets incremented by 1 by first setState call, once it is done, the counter is then incremented to 2. This update is done in a synchronous manner.

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

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