Categories
javascript reactjs web development

React.js – How to use Refs in React.js

Using refs in React.js

Hey guys 👋🏻,
In this article, let us cover the topic of How to use Refs in React.js

Let us investigate why React.js, a library that keeps your code away from DOM manipulation, keeps its doors open for you to access. React rethinks a view as a result of a state of a component. It provides JSX, a syntactic sugar over JavaScript, to design the view layer and then modifies the DOM itself rather than giving the control to the developer.

Still, the React team provided escape routes and kept the library open for certain situations that go beyond the scope of what React is designed for.

Creating Refs

Refs are escape routes and it’s better to avoid them whenever possible. When we obtain a DOM element using ref and then later modify its attribute, we might enter into a conflict with React’s diff and update approach.

Let’s start with a simple component and grab a DOM element using ref, assuming that you already know how to set up a basic react app.

In the above piece of code, we are using a react hook useRef to create and initialize a variable called buttonRef. We then assign buttonRef to ref attribute on button JSX element.

Using React refs

As we discussed earlier in this article we are declaring views based on the state, and though we are still altering the state using functions, we are not in direct control of the DOM changes. But in a few use cases, it makes sense to introduce refs in your code.

Focus Control

To better understand the problem statement let’s storify the situation.

Alex is a software development intern at Metflix Inc. and his manager has given him the task of creating contact forms. The manager has asked him to focus on the first input element in the form when a modal is opened. Alex is confused about how he can achieve this in React.js. Let’s help Alex out.

The first thing we need to do is to get a reference to the input.

Next, when our modal loads, we imperatively call focus on our input ref.

Note: You need to access the element through the current property of the ref you declare.

Detect if an element is contained

Similarly, we would want to take an action in the app when an event is dispatched. Like close the modal when the user clicks outside of it.

Here, we are checking if the user click is out of the modalRef limit. If it is we are calling close() function from props to close the modal.

Integrating DOM-based libraries

Like React, there are other utilities and libraries outside its ecosystem that have been in use for years. To use such libraries, refs come in handy.

GreenSock library is a popular choice for animation examples. To use it, we need to send a DOM element to any of its methods.

Let’s go back to our modal and add some animation

Forwarding Refs

Refs are useful for specific actions. The examples shown are a little simpler than what we usually find in a real-life web application. We need to deal with complex components and we barely use plain HTML elements directly. It’s common to use a ref from one component in another component.

The issue now is that passing a ref to this component will return its instance, a React component reference, and not the input element we want to focus on like in our first example.

React provides forwardRef, which allows you to define internally what element the ref will point at.

Now, when a parent component passes a ref value, it’s going to obtain the input, which is helpful to avoid exposing the internals and properties of a component and breaking its encapsulation.

So this is it for this article. Thanks for reading.

If you enjoy my articles, consider following me on Twitter for more interesting stuff :

⚡Twitter : https://twitter.com/The_Nerdy_Dev

Don’t forget to leave a like if you loved the article. Also share it with your friends and colleagues.

Alt Text

Categories
javascript web development

Understanding Primitives and Reference Types in JavaScript

Hey guys 👋🏻,
In this article, let us cover the topic of Understanding Primitives and Reference Types in JavaScript.

Image description

Primitive value is stored directly in the location that the variable accesses. And the Reference values are objects that are stored in the heap. Reference value stored in the variable location is a pointer to a location in memory where the object is stored. This is something that I will demonstrate just a bit later. So stay with me.

Basic Primitive Types and Reference Types

JavaScript supports 5 primitive data types: number, string, Boolean, undefined, and null.

These types are referred to as primitive types because they are the basic building blocks from which more complex types can be built. Of these five, only number, string, and boolean are real data types in the sense of actually storing data.

Undefined and null are types that arise under special circumstances. The primitive type has a fixed size in memory. For example, a number occupies eight bytes of memory, and a boolean value can be represented with only one bit.

Contrary to this, reference types can be of any length. They don’t have a fixed size.

For primitives, they are always copied as a whole value whereas for reference types they are copied by reference.

For variables that hold values we only compare their values whereas in case of reference types like objects, it is not the case.

Consider this example :

Image description
Image description

The above log gives true because both a and b are referencing to the exact same memory location. So let us say the memory for the arrow was allocated at some memory address of say 4k. So a is a reference that will point to the array object that is sitting at memory address 4k. So if you then assign a to b like we do above, then we have a new reference that points to the exact same object in the memory. So therefore since both the references point to the exact same object in the memory that is why it gives true for the strictly equality comparison between a and b (for the above log).

But if I declare another array with the exact same content say c.

and then do this :

Image description

Then the above log will resolve to false because this new array will get allocated at a different memory location say 5k. So if we compare a and c using a strict equality comparison, then it will resolve to false because both the references a and c point to different memory locations namely 4k and 5k respectively and hence you get false.

Now consider example for primitives. For this case you just compare the values. So if we have :

and then we say :

Then for the above log we make sure that both the type and the value are equal for the things (primitives under comparison). Both are 3 and both are numbers so hence we get true for this.

Next if we say

This will resolve to false because 3 and 4 are not equal.

So this is it for this article. Thanks for reading.

If you enjoy my articles, consider following me on Twitter for more interesting stuff :

Image description

⚡Twitter : https://twitter.com/The_Nerdy_Dev

Don’t forget to leave a like if you loved the article. Also share it with your friends and colleagues.

Alt Text

Categories
backend frontend javascript web development

What, Why and How to Validate ?

Hey guys 👋🏻,
In this article, let us learn about validation in case of application and learn about What, Why and How to Validate ?.

What, Why and How to Validate ?

To ensure that the data that you work with is the data in correct format, you need validation for it.

Let us answer these questiions :

Why should we use validation ?

Why would you add data validation to your application ?

When we have a user interacting with our website we typically have forms in any web application that we build. The bigger your application is the more data you will need from your users at some point of time. So we have that form which the user of the website interacts with and in the end this form is submitted with the POST request.

Then a request to the backend is sent along with the form data.
On our backend, we typically interact with the database using our server side logic or we may typically write our data into a file using the fs core module of Node.js. But in the end we take that data we receive and want to store it. This is why the need for data validation and sanitization arises.

If a user in our application would try to login with something that is not a valid email address, we should not allow access to the user, so we should prevent the user from entering something incorrect and getting access for that.

This is where we want validation to kick in.

How to validate and provide a good user experience ?

Obviously we got a user entering some data onto the form (Form Input) and let us say a Node.js application running on the server. We got a couple of places where we can validate, for example, we can validate on the client side of our application.

So right before any request hits the server, we can write some JavaScript, that for example checks the input at every keystroke and checks the input whilst the user is working on the form and then you can display an error right in the browser and this can greatly enhance the user experience on the client side for us.

This type of validation is totally optional because the user can see that code, user can change the validation and user can disable the JavaScript in the browser.

👉🏻This is not the protection that can secure you against incorrect data being sent to the server. This is not a secure solution it just is there to improve the user experience thing, so just to render proper error messages.

So,

we will focus on Server Side Validation. This is what we do with Node.js. This code can’t be used by the user, the user cannot disable this validation code that we define on the server side because this happens on the server not in the browser and this is the crucial part where we need to have validation to filter out incorrect values and this is what we will focus on. This ensures that we work with valid data in our node application and if we do plan on storing it ultimately we do store correct data in our database. There is also built in validation which we can use in databases like Mongo. This can be last resort. If we have strong validation on the server side no invalid data will be able to reach the database because you already filtered the incorrect data in the server side validation.

Validation at database level is also optional.

You must have to validate at server side at all means. If the validation fails, you must have to return an error message in user interface with helpful message and do not reload the page with the user input intact with the correct error message rendered in our user interface. This is because reloading offers a horrible experience to the end user and this would clear up all your form data and you would have to enter all the data again !

Example – Discussion on Validation for a Registration Page :

Some common validations for validating the form controls of a registration page are these :

✔ Check for the correctness of the mail. It is according to the format (must not be in bad format). It also must possess @ symbol
✔ Password must be atleast 6 characters long.
✔ Password and ConfirmPassword fields must match.

etc. etc.

Please note
You are not just restricted to above validations, you could have other validations as well for your form controls.

If you want to perform validation for your APIs that you have written using Express, you can make use of packages like

1. Express Validator

Image description

Though you could also make use of another npm package which is Joi for performing validation.
2. Joi

Image description

Now typically we want to validate for NON-GET requests because generally these are the cases in which the user will send some data to the server.

Sanitizing user input

We can ensure as an example that there is no extra whitespace in the string that is passed by the user on the left or on the right
You can normalize the email that is converted to lowercase or things like that. There is a couple of things that you can ensure that the data you get back is valid but is also stored in the uniform way without any extra whitespace or anything like that.
This is what we mean by Sanitization.

Sanitizing input is also that makes sense to be done. For sanitizing the email we can make use of the normalizeEmail method that is available on express-validator

Image description
Similarly, for sanitizing the password we can make use of the trim method that is also provided to us by the express-validator

Sanitizing data is important to ensure that your data is stored in the uniform format.

So this is it for this article. Thanks for reading.

If you enjoy my articles, consider following me on Twitter for more interesting stuff :

Image description

⚡Twitter : https://twitter.com/The_Nerdy_Dev

Don’t forget to leave a like if you loved the article. Also share it with your friends and colleagues.

Alt Text

Categories
frontend javascript web development

My Top 3 Server Side Technologies. What are yours ?

Hey guys 👋🏻,
In this article, I will unveil My Top 3 Server Side Technologies that I work with.

Image description

Node.js

Image description

Node.js is a JavaScript Runtime for building scalable network applications. It is blazing fast and it is best to use when we have large number of concurrent connections active at a given point of time and requires immediate response time.

Django

Image description

Django is a backend development framework that provides you a lot of things out of the box (authentication system for example). It allows you to focus on building the application without re-inventing the wheel.

Ruby on Rails (ROR)

Image description
Ruby on Rails is just like Django which uses batteries included approach. It helps developers to build scalable applications because it abstracts and simplifies common repetitive tasks.

What are your Top 3 ? Let me know in the comments section

So this is it for this article. Thanks for reading.

If you enjoy my articles, consider following me on Twitter for more interesting stuff :

Image description

⚡Twitter : https://twitter.com/The_Nerdy_Dev

Don’t forget to leave a like if you loved the article. Also share it with your friends and colleagues.

Alt Text

Categories
frontend javascript web development

Best FREE resources for learning ES6

Hey everyone 👋🏻,

In this article, I will share some of the BEST FREE resources for learning ES6 along with the links to those articles.

ES6

Image description

let –
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/let

const –
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/const

Variables and Scoping in ES6 –http://2ality.com/2015/02/es6-scoping.html

Template Literals –
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals

Arrow Function Expressions – https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions

Arrow Functions VS Normal Functions –
http://exploringjs.com/es6/ch_arrow-functions.html#sec_arrow-func-vs-normal-func

for-of loop – https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for…of

default parameters –

named params –

http://exploringjs.com/es6/ch_parameter-handling.html#sec_named-parameters

rest params –

https://medium.freecodecamp.org/es6-tagged-template-literals-48a70ef3ed4d

Tagged Templates –

https://medium.freecodecamp.org/es6-tagged-template-literals-48a70ef3ed4d

De-structuring Assignment 

Shorthand Properties 

ES6 Modules
-> CommonJS
-> AMD

https://auth0.com/blog/javascript-module-systems-showdown/

Promises
-> then –
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/then
-> catch –
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/catch
-> finally –
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/finally
-> all –
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/all

Classes in ES6 –
http://exploringjs.com/es6/ch_classes.html

Object.assign –
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/assign

Async Await –
http://exploringjs.com/es2016-es2017/ch_async-functions.html

Symbols –
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Symbol

Maps and WeakMaps –

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/WeakMap

Sets and WeakSets –

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Set

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/WeakSet

Iterator Protocol –
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols#The_iterator_protocol

Proxy –
https://codeburst.io/understanding-javascript-proxies-by-examining-on-change-library-f252eddf76c2

Generators –

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Generator

Iterators and Generators –
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Iterators_and_Generators

function*
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/function*

yield
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/yield

yield*

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/yield*

So this is it for this article. Thanks for reading.

If you enjoy my articles, consider following me on Twitter for more interesting stuff :

Image description

⚡Twitter : https://twitter.com/The_Nerdy_Dev

Don’t forget to leave a like if you loved the article. Also share it with your friends and colleagues.

Alt Text
Categories
frontend javascript web development

Frontend Developer Roadmap

Hey guys 👋🏻,
In this article, let us understand the roadmap that will help you in becoming a Frontend Developer in 2021.

Image description

Step 1:

First learn HTML, CSS and JavaScript

Image description

Step 2:

Work on your own projects to build skills and then work on LIVE projects. Go grab some internship to get some working experience on various technologies.

Image description

Step 3:

Pick and learn one frontend framework of your choice. Again go back to Step 2. After Step 2, proceed to Step 4.

Image description

Step 4:

Start applying for Frontend Developer jobs or become a Freelancer once you start to feel confident of your skills.

So this is it for this article. Thanks for reading.

If you enjoy my articles, consider following me on Twitter for more interesting stuff :

Image description

⚡Twitter : https://twitter.com/The_Nerdy_Dev

Don’t forget to leave a like if you loved the article. Also share it with your friends and colleagues.

Alt Text
Categories
javascript web development

Where to filter the data – backend or frontend ?

✨Where to filter the data – backend or frontend ?  

 

Hey everyone,

In this article, let us discuss about a very important question regarding filtering the data that we get from the database or API. So the question is : 

Where exactly should we filter the data ? 

🤔 Backend … ? 

🤔 Frontend … ? 

Well, the answer is : 

It depends. 

Let us discuss now : 

So if you have a a large amount of data, it is better to implement the filtering logic on the backend and let the database handle all the heavy lifting for us. Contrary to this, if you are dealing with less amount of data, you can do the filtering logic on the frontend.

In general, if you are working with a million recordset (as an example) and there are tons of users trying to access those records at the very same, then in such cases it does not make sense to send a million recordset to every user who is currently accessing the website. It simply does not make sense because it will simply bring your website down, so what we do in such cases is that we setup a record limit (kind of we send the data in batches) by using a features like database cursors. So kind of with the cursors in place, you can fetch the data in batches in some sort of pagination etc. Consider a big ecommerce website like Amazon, this is how they handle that amount of data in a nutshell.

For less amount of data, you could retrieve the data from the backend and then use the filtering logic on the frontend.

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
html javascript vuejs web development

✨Top 5 resources to learn Vue.js [in no particular order]

✨Top 5 resources to learn Vue.js

Hey everyone 👋🏻,

In this article, I will be mentioning the top 5 resources that I highly recommend if you want to learn Vue.js.

PS : I am not an affiliate of any of these resources/courses. These are just some of my personal recommendations if you are looking to learn Vue.

Introduction

Alt Text

Vue is a progressive framework for building user interfaces. Unlike other monolithic frameworks, Vue is designed from the ground up to be incrementally adoptable. The core library is focused on the view layer only, and is easy to pick up and integrate with other libraries or existing projects.

Here are the top 5 recommendations (in no particular order) of the courses that you should definitely check out for learning Vue.

1. Build Web Apps with Vue 3 and Firebase by Shaun Pelling a.k.a The Net Ninja (rated 4.8)

image

Shaun is a gifted teacher. He knows how to explain stuff in a very easy and lucid manner. This course will definitely take your knowledge to the next level if you are looking to learn this specific technology.

Here is what this course covers

Learn how to create Vue 3 applications from the ground-up

Get in-depth knowledge of Vue features like the Vue Router, Vue CLI, Options API, Composition API, Teleport etc

Get hands-on & in-depth experience using the latest Vue 3 features (such as the Composition API)

Learn how to use Firebase as a back-end to your Vue applications (as a database, authentication service, hosting etc)

Build & deploy 4 real-world web apps with Vue & Firebase
Learn how to implement an authentication system into your Vue js apps using Firebase Auth

Become a Vue 3 ninja!

Course Link :

https://www.udemy.com/course/build-web-apps-with-vuejs-firebase

2. Vue.js – The Complete Guide by Maximilian Schwarzmuller ( rated 4.8)

image

This course as the name can probably tell you covers the internals of Vue in great detail. The course starts from the very basics like What Vue.js is and how it works and later on moves to more complex and advanced topics

Here is what this course covers

What is VueJS and Why would you use it?

The Basics (including the basic Syntax, Understanding Templates and much more!)

How to Output Reactive Data & Listen to Events

Interacting with DOM (Rendering Lists, Conditionally attaching/ detaching Elements …)

Setting up a Development Environment and Workflow

Using Components (and what Components are to begin with)

A Deep Dive Look Behind the Scenes of Vue

Binding to Form Inputs

Sending Http Requests to Backend APIs

Authentication & Vue

How to make your App more Beautiful with Animations and Transitions

How to create an awesome Single-Page-Application (SPA) with Routing

How to improve State Management by using Vuex

How to Deploy the App

and more …

Course Link :

https://www.udemy.com/course/vuejs-2-the-complete-guide

3. Vue Mastery

This is a complete path for learning Vue.js from some prominent industry experts pertaining to the technology.

image

image

Here is what this course covers

Their courses are distributed in form of paths. You may want to try them out as well.

image

Course Link :

https://www.vuemastery.com/courses

4. VueSchool.io

image

Here is what this course covers

image

You may want to try their complete suite of courses to enhance your Vue.js Knowledge. So down below, you can find the link for their website :

Course Link :

https://vueschool.io/courses

5. Vue.js Documentation (a must thing to refer)

image

Docs link :

https://v3.vuejs.org/

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.

Categories
ejs html javascript mongodb nodejs template engines web development

Rendering Dynamic Content and Template Engines

✨Rendering Dynamic Content and Template Engines

Hey everyone 👋🏻,

In this article, let us learn about how we can render dynamic content to the client (which is not static). Let us first touch briefly on what a template engine is because rendering dynamic content is closely related to what a template engine will help us in achieving.

Template Engines – a brief overview

Image description

A template engine is software designed to combine templates with a data model to produce multiple pages that share the same look throughout the site. These are the views in an MVC project.

So this helps us in putting dynamic content on our HTML pages.

We got a HTML like template (technically not HTML) which is typically a file that contains a lot of HTML like content in it but with some placeholders plugged into it and then we have a server (a Node.js Express server or any other server) serving the Node/Express content and then you have a templating engine.
that replaces placeholders with HTML content but that content is generated on the server dynamically on the fly taking that dynamic content into account.

Some of the common template engines :

1. EJS

EJS Uses normal html and plain javascript in your templates.

Image description

EJS provides us clean syntax that easily mixes with HTML and provides the flexibility to write the JavaScript code inside the templates.

Dynamic content to be rendered in the above example is name. The value of the name variable will be rendered as an HTML page’s paragraph with value of name getting rendered on the fly.

2. Pug

PUG uses minimal HTML and custom template language.

Image description

3. Handlebars

Handlebars uses normal HTML and custom template language

Image description

The side effect of Handlebars template compared to Pug is that we cannot run any logic in the Handlebars template we need to pass a variable that has a value true or false(i.e logic is performed outside and passed into hbs template) and then we can render dynamic content.

This keeps our templates lean and all our logic should live while making sure that all our logic lives in our backend code. It works on the philosophy of less logic in the template and more logic in the node express code.
So you have to prepare everything there so that inside the template you don’t have to write any JavaScript expressions.

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.

Categories
css html javascript mongodb nodejs web development

(2021) – Web Developer Full Course : HTML, CSS, JavaScript, Node.js and MongoDB

✨Web Developer Full Course

Alt Text

I recently started to create a Full Web Developer Course on my YouTube Channel and recently finished with the HTML and the CSS Section of this FREE course. More videos will be up on upload.

HTML Section

CSS Section

JavaScript Section

This section covers the basics of JavaScript along with the modern features that the language offers. We cover concepts like :

  1. JavaScript Basics (variables, loops, conditionals, functions)
  2. JavaScript Types (Strings, Numbers, Objects, Booleans, Functions, Symbols)
  3. Immediately Invoked Function Expressions
  4. Document Object Model (DOM) – Querying, Traversal, Inserting and Removing Elements from the DOM
  5. Arrays and Iterables
  6. Mutator methods – push, pop, shift, unshift, splice
  7. Other array methods like – slice, indexOf, findIndex, find, sort, reverse
  8. Higher Order Methods – filter, reduce, map
  9. Split and Join Methods
  10. The spread operator
  11. Sets and Maps
  12. Understanding the this keyword in JavaScript
  13. Overview of Objects, Constructor Functions, Classes, OOP, Instance and Static Methods, Inheritance
  14. Events – Adding and Removing Event Listeners
  15. Event Capturing – Bubbling Phases, Propagation and Event Delegation
  16. Asynchronous JavaScript – Event Loop (Call Stack, Message Queue)
  17. Asynchronous JavaScript – Understanding Promises and Error Handling
  18. Asynchronous JavaScript – Promise.race, Promise.all, Promise.allSettled
  19. Demystifying Async Await, From Promises to Async Await
  20. Scopes in JavaScript, Closures
  21. Symbols in JavaScript
  22. Iterators and Generators in JavaScript
  23. The Concept of Pure and Impure Functions in JavaScript
  24. Understanding Hoisting in JavaScript

AND MORE….

A lot of exercises and projects were made in this section of the course.

Here are the Projects that we made in this JavaScript Section :

Building COVID-19 Tracker Application using JavaScript and Mapbox

Making a Todo List Application in JavaScript using Custom Events

Implementation of Infinite Scroll in JavaScript

10 JavaScript Projects in 2 Hours 

Node.js Section
COMING SOON

MongoDB Section
COMING SOON

Make sure to subscribe to the channel for more such videos.
A lot of AWESOME videos are coming this month… So make sure to SUBSCRIBE to the channel for more amazing videos.

Follow me on Twitter for more updates: https://twitter.com/The_Nerdy_Dev