Search

What Is a React Component? Write Your First React Component

Prior to ReactJS, Popular frameworks like Angular and Ember were focused more towards model/view/controller like patterns known as MVC. These frameworks tried to provide more functionalities and solve most front-end development problems. ReactJS, however, chose to follow a different path, focusing primarily on views and how we can efficiently render views, thus popularising Component-based Architecture in web development.  I wouldn’t go so far as to say the creators of ReactJS invented the Component-based Architecture pattern, but for sure they saw its benefits and helped popularize this pattern for web development.  But first, what is Component-based Architecture? Component-based Architecture In web development, final output is a fully functional UI. According to component-based architecture, we should see the complete UI as a combination of multiple smaller, reusable, composable, functional components and we should approach the problem in similar fashion. We should build multiple small, composable, functional components which can work together as a complete solution. What is component? So, we understand that in component-based architecture, we are supposed to build plenty of smaller components. But what is a component and how does it look like? The word "component" in software industry means a software package, a service or any module which encapsulate a set of related functionalities. In the context of UI development, a component means a UI element or a collection of UI elements which together provide some set of functionalities. A component could be as small and simple as a heading component which is builtwith single H1 tag and its text or it could be as complex as accordion or tabbed navigation. ReactJS also encourages web developers to build smaller, reusable, composable components.Benefits of using Component Architecture There are lot of discussions about the benefits of using Component Architecture. Some people feel that if we break down the UI in multiple components interacting with each other,then the code base will have too many components and will eventually make the project un-maintainable. But still, this architecture has following benefits: Reusability: It would always be great to avoid writing new code as much as we can and use the existing well tested functionalities. If we have collection of well tested reusable components then definitely, the overall output would be more robust. Faster Development: Reusing the same set of components will eventually take less time to develop a functionality. Composability: A big functionality is nothing but a collection of multiple small functionalities. Similarly, it is simpler to build a bigger functionality efficiently if we can compose multiple small components together. Less Maintainability: More reusability means less code and less code will always lead to less maintenance of code base.React Components React component is basically a collection of one or many UI elements which renders a complete functionality. It can show different behaviours based on different parameters. In ReactJS, these parameters are knownas state of component and props passed to component. So how does a React component looks like? A very simple components looks something like this:import React from "react";  function Greeting({ name }) {    return < h1 >{`Hello ${name}`}</h1>;  }  ReactDOM.render(<Greeting name="Gully Boy" />, document.getElementById("root"));Alright. But<Greeting /> is not recognised by web browsers so won't it throw an error? Above code uses JSX (Syntax extension for JavaScript) and there are tools which actually converts JSX into something understandable by JavaScript engines of web browsers.  JSX JSX is a library which allows us to write HTML (or XML) like syntax in JavaScript file. Then this code goes through a tool which converts it into something understandable by JavaScript engines. It allows us to write HTML in JS. It gives a syntax { <Any JS code >}, inside curly bracket, we can write JS code. But still how does the final React component looks like? Below code snippet is a final conversion of above Greeting component. import React from "react";  function Greeting({ name }) {    return React.createElement("h1", null, `Hello ${name}`);  }  ReactDOM.render(  React.createElement("Greeting", { name: "Gully Boy" }, null),  document.getElementById("root")  ); React.create Element is part of React API which actually defines a React element. This data structure will be used by React to render the DOM element later. So now, we understand the need of JSX and benefits of using JSX, We will be using React components using JSX in rest of the article.  Classification of React Components Based on Interactivity Before going into the classification, we need to understand what a state means in React component. state is information that a component itself maintains and which changes with time. The state affects the UI and/or the behaviour of the component. There are two types of components based on interactivity: Stateless Component: When a React componentdoesn't have its own state and it just renders based on the information passed to component (props) or a hardcoded information within the component then such components are called as stateless component. Such type of component doesn't provide any user interactivity with component. For Ex: above Greeting component <Greeting name="John Smith" /> is a stateless component as it just renders the information (in this case name props) passed to it. Stateful Component: There is other type of component which possesses state. This means based of the state behaviour of component changes. These types of components are known as stateful components. For Example a counter component below:import React, {useState} from 'react';  function Counter() {  const [value, setValue] = useState(0);  const increment = () => {  setValue(value + 1);  }  const decrement = () => {  setValue(value - 1);  }  return (  <div>  <button type="button" onClick={increment}>Decrement</button>  <span>{value}</span>  <button type="button" onClick={decrement}>Decrement</button>  </div>  );  }  export default Counter;Counter component has a state value which changes when user clicks on increment or decrement button. there is a span tag which displays the state value and it also gets updated based on user action. So this component is an example of stateful component. Based on Programming Methodology Counter component has a state value which changes when user clicks on increment or decrement button. there is a span tag which displays the state value and it also gets updated based on user action. So this component is an example of stateful component. Based on Programming Methodology There are two type of components based on Programming Methodology Class based Component: A React component can be JavaScript class which implements render method of ReactJS and extends React.Component class. Generally if a component has any state or need to implement any React lifecycle method then we create a class based component. Class based componentmust implement the render lifecycle method which returns the JSX. Stateless component can also be implemented as class based component. For example, Above <Greeting /> component can be implemented as class based component like below:import React from 'react';  class Greeting extends React.Component {  constructor(props) {  super(props);  }  render() {  return < h1 >{`Hello ${this.props.name}`}</h1>;  }  }  export default Greeting; Functional Component: A React component can be JavaScript function which returns JSX. Before Hooks which means before React v16.8, functional component was used only for building stateless component. Functional component takes props as argument and returns JSX. Writing functional code is always better in comparison to class based component because transpiled code for functional component is always shorter than class based component. For example, First implementation of <Greeting /> at the top is functional component. Based on Functionality There are two types of components categorised based on functionality. One typeimplementsbusiness logic and the other type is more inclined towards UI. Presentational Component: React components which decide the look and feel of UI are called presentational component. These components can be stateful or stateless components. State of these components are normally UI level state instead of application (business logic) state. These components are reusable and often used to have independent styles. For example: above Greeting component is a presentational component which can we be reused multiple places in application. Container Component: React component which mainly deals with application level state, rarely contains HTML tags and interact with API data are known as container component. This categorisation is basically separation of UI logic and application logic.Component and its lifecycle In React JS, class-based components are extended from React.Component class which provides several lifecycle methods to component. render is also a life cycle method which must be implemented in React component. Other lifecycle methods are optional and can be used to gain more control over the React component. As ReactJS has evolved with time, few lifecycle methods are no longer supported and will be removed from library in coming update. In this article, we will look into the lifecycle methods which are supported by library version 16.4+.  React lifecycle. To understand component's lifecycle methods and their invocation orders, we can divide all the methods in three broad category: Mounting, Updating, Unmounting Mounting: When component mounts then first of all constructor method (if present) is called. constructor method takes props as argument and pass props to the constructor method of React.Component class. Refer the example of class based component above. then getDerivedStateFromPropsstatic method will be invoked. getDerivedStateFromPropstakes two argument - props and state and returnsan object to update the state or returnsnull to update nothing. This lifecycle method is used when the state is dependson props. After getDerivedStateFromPropsmethod, render method is being called which returns the JSX. After render, componentDidMount is called which is the last method in mounting phase. We normally put API calls in componentDidMount lifecycle method. To summaries the mounting of component:constructor constructor(props) { super(props); // code here }getDerivedState From Props static getDerivedStateFromProps(props, state) {  // code here  // return updated state object or null  } render render() {  // code here  } componentDidMount componentDidMount() {  // code here  } Updating:  After a component is mounted, A React component is changed either when the state of component or props passed is changed. on update, first getDerivedStateFromPropsstatic method is called which returns the object to update the state or return null to update nothing. Then shouldComponentUpdate lifecycle method is called which takes two arguments (nextProps and nextState) and return a boolean. This method decides whether render method should be invoked or not. If this method returnstrue then render method will be invoked otherwise component will not get updated. This method is used to optimise the React component by reducing the number of re-renders. if shouldComponentUpdate return true (which is also the default return value of method) then render method will be invoked which updated the component based on updated state or new props. After render method getSnapshotBeforeUpdate method is called. this method is invoked right before the rendered output is committed to DOM. It takes two arguments prevProps and prevState. this method gives access to DOM before React is going to update it with recent changes. For example, you can access last scroll position before update (re-render). Value returned by getSnapshotBeforeUpdate will be passed to componentDidUpdate method which is the next lifecycle method invoked. componentDidUpdate is called right after update occurs. This method takes three arguments prevProps, prevState and snapshot. last argument snapshot will be the value returned from getSnapshotBeforeUpdate lifecycle method. To summarise update phase of component:getDerivedState From Props static getDerivedStateFromProps(props, state) {  // code here  // returns updated state object or null  } should Component Update shouldComponentUpdate(prevProps, prevState) {  // code here  // returns true to re-render the component otherwise return false.   // default is true  } render render() {  // code here  } getSnapshot Before Update getSnapshotBeforeUpdate(prevProps, prevState) {  // code here  } component Did Update componentDidUpdate(prevProps, preState, snapshot) {  // code here  } Unmounting: Last phase of React component is unmount. it invokes the last method of React component's lifecycle componentWillUnmount. this method is called before the component is unmounted and destroyed. Normally, clean up code is put in componentWillUnmount method. we should not call setState method here as component is never going to be re-rendered after unmount. To summarise:componentWillUnmount  componentWillUnmount() {  // code here  }Set up a React project As JavaScript has evolved and tooling has become an essential part of web development. There are many approaches to start a React project but the most popular one is create-react-app (popularly known as CRA). create-react-app is available as NPM module which means to use CRA, one must have NodeJS and NPM installed on machine. Create React project with CRA First check the NodeJS and NPM installation on machine by executing following command: node --version  npm --version  npx –version In case NodeJS is not install then download and install it from. Once it is confirmed that NodeJS and NPM is installed on system then execute following command to create a React project: npx create-react-app My First React Project NPX command comes with NPM. It is used to use any NPM without actually installing the NPM. above command will create a new React project with latest version of create-react-app in your current directory. Execute following command to run the project: cd My First React Project npm start This would start a local server at port number 3000 and open default React page in browser.Understanding project generated by CRAAbove image shows the files and folder generated by CRA. let us go through it and understand: package.json: This file contains NPM dependencies, NPM scripts, project name, version etc... public folder: All public assets will be present in public folder like index.html, image or logo etc... src folder: All our JS code including React components will be present in src folder. CRA configured our React project with all the needed tooling required for web development. It configured Webpack, dev server with hot reload ( on file save browser reloads the page to reflect latest change), Eslint, react-testing-library for unit testing React components etc... src/index.js is the starting point of our React project. Project also has one sample React component App.js. You can make changes to App.js and it will be reflected on browser. What type of React Component should I build in 2020 So far, we have learnt different ways of writing React component. Now it is time to choose which pattern should you choose for writing React components. As we have discussed in previous article that ReactJS is moving towards functional programming paradigm and with the introduction of hooks in version 16.8, Writing functional component fulfils most of our use cases.Let's create our first stateful functional component. We will be building a simple counter component. The final output looks like this: Counter component code: import React, { useState } from "react";  import "./Counter.css";  function Counter() {  const [count, setCount] = useState(0);  const increment = () => {  const updatedCount = count + 1;  setCount(updatedCount);  };  const decrement = () => {  const updatedCount = count - 1;  setCount(updatedCount);  };  return (  <div className="counterContainer">  <button type="button" onClick={decrement}>  - </button>  <span>{count}</span>  <button type="button" onClick={increment}>  +  </button>  </div>  );  } export default Counter; Styles are added in Counter.css .counterContainer {  background-color: #fff;  font-size: 24px;  font-weight: 500;  border: 1px solid #0874ce;  border-radius: 3px;  box-shadow: 1px 1px 4px 0 #0084ff;  }  .counterContainer button {  outline: none;  border: none;  width: 50px;  height: 40px;  background-color: transparent;  font-size: 24px;  font-weight: 500;  cursor: pointer;  }  .counterContainer span {  color: #0084ff;  } We have created a fully functional counter component which can be used anywhere in React application.

What Is a React Component? Write Your First React Component

7K
What Is a React Component? Write Your First React Component

Prior to ReactJS, Popular frameworks like Angular and Ember were focused more towards model/view/controller like patterns known as MVC. These frameworks tried to provide more functionalities and solve most front-end development problems. ReactJS, however, chose to follow a different path, focusing primarily on views and how we can efficiently render views, thus popularising Component-based Architecture in web development.  

I wouldn’t go so far as to say the creators of ReactJS invented the Component-based Architecture pattern, but for sure they saw its benefits and helped popularize this pattern for web development.  

But first, what is Component-based Architecture? 

Component-based Architecture 

In web development, final output is a fully functional UI. According to component-based architecture, we should see the complete UI as a combination of multiple smaller, reusable, composable, functional components and we should approach the problem in similar fashion. We should build multiple small, composable, functional components which can work together as a complete solution. 

What is component? 

So, we understand that in component-based architecture, we are supposed to build plenty of smaller components. But what is a component and how does it look like? 

The word "component" in software industry means a software package, a service or any module which encapsulate a set of related functionalities. In the context of UI development, a component means a UI element or a collection of UI elements which together provide some set of functionalities. A component could be as small and simple as a heading component which is builtwith single H1 tag and its text or it could be as complex as accordion or tabbed navigation. ReactJS also encourages web developers to build smaller, reusable, composable components.

Benefits of using Component Architecture 

There are lot of discussions about the benefits of using Component Architecture. Some people feel that if we break down the UI in multiple components interacting with each other,then the code base will have too many components and will eventually make the project un-maintainable. But still, this architecture has following benefits: 

  • Reusability: It would always be great to avoid writing new code as much as we can and use the existing well tested functionalities. If we have collection of well tested reusable components then definitely, the overall output would be more robust. 
  • Faster Development: Reusing the same set of components will eventually take less time to develop a functionality. 
  • Composability: A big functionality is nothing but a collection of multiple small functionalities. Similarly, it is simpler to build a bigger functionality efficiently if we can compose multiple small components together. 
  • Less Maintainability: More reusability means less code and less code will always lead to less maintenance of code base.

React Components 

React component is basically a collection of one or many UI elements which renders a complete functionality. It can show different behaviours based on different parameters. In ReactJS, these parameters are knownas state of component and props passed to component. So how does a React component looks like? 

A very simple components looks something like this:

import React from "react"; 
function Greeting({ name }) { 
  return < h1 >{`Hello ${name}`}</h1>; 
} 
ReactDOM.render(<Greeting name="Gully Boy" />, document.getElementById("root"));

Alright. But<Greeting /> is not recognised by web browsers so won't it throw an error? Above code uses JSX (Syntax extension for JavaScript) and there are tools which actually converts JSX into something understandable by JavaScript engines of web browsers.  

JSX 

JSX is a library which allows us to write HTML (or XML) like syntax in JavaScript file. Then this code goes through a tool which converts it into something understandable by JavaScript engines. It allows us to write HTML in JS. Igives a syntax { <Any JS code >}, inside curly bracket, we can write JS code. 

But still how does the final React component looks like? Below code snippet is a final conversion of above Greeting component. 

import React from "react"; 
function Greeting({ name }) { 
  return React.createElement("h1", null, `Hello ${name}`); 
} 
ReactDOM.render( 
React.createElement("Greeting", { name: "Gully Boy" }, null), 
document.getElementById("root") 
); 

React.create Element is part of React API which actually defines a React elementThis data structure will be used by React to render the DOM element later. So now, we understand the need of JSX and benefits of using JSX, We will be using React components using JSX in rest of the article.  

Classification of React Components 

Based on Interactivity 

Before going into the classification, we need to understand what a state means in React component. state is information that a component itself maintains and which changes with time. The state affects the UI and/or the behaviour of the component. 

There are two types of components based on interactivity: 

  • Stateless Component: When a React componentdoesn't have its own state and it just renders based on the information passed to component (props) or a hardcoded information within the component then such components are called as stateless component. Such type of component doesn't provide any user interactivity with component. For Ex: above Greeting component <Greeting name="John Smith" /> is a stateless component as it just renders the information (in this case name props) passed to it. 

  • Stateful Component: There is other type of component which possesses state. This means based of the state behaviour of component changes. These types of components are known as stateful components. For Example a counter component below:

import React, {useState} from 'react'; 
function Counter() { 
const [value, setValue] = useState(0); 
const increment = () => { 
setValue(value + 1); 
} 
const decrement = () => { 
setValue(value - 1); 
} 
return ( 
<div> 
<button type="button" onClick={increment}>Decrement</button> 
<span>{value}</span> 
<button type="button" onClick={decrement}>Decrement</button> 
</div> 
); 
} 
export default Counter;

Counter component has a state value which changes when user clicks on increment or decrement button. there is a span tag which displays the state value and it also gets updated based on user action. So this component is an example of stateful component. 

Based on Programming Methodology 

Counter component has a state value which changes when user clicks on increment or decrement button. there is a span tag which displays the state value and it also gets updated based on user action. So this component is an example of stateful component. 

Based on Programming Methodology 

There are two type of components based on Programming Methodology 

  • Class based Component: A React component can be JavaScript class which implements render method of ReactJS and extends React.Component class. Generally if a component has any state or need to implement any React lifecycle method then we create a class based component. Class based componentmust implement the render lifecycle method which returns the JSX. Stateless component can also be implemented as class based component. For example, Above <Greeting /> component can be implemented as class based component like below:

import React from 'react'; 
class Greeting extends React.Component { 
constructor(props) { 
super(props); 
} 
render() { 
return < h1 >{`Hello ${this.props.name}`}</h1>; 
} 
} 
export default Greeting; 
  • Functional Component: A React component can be JavaScript function which returns JSX. Before Hooks which means before React v16.8, functional component was used only for building stateless component. Functional component takes props as argument and returns JSX. Writing functional code is always better in comparison to class based component because transpiled code for functional component is always shorter than class based component. For example, First implementation of <Greeting /> at the top is functional component. 

Based on Functionality 

There are two types of components categorised based on functionality. One typeimplementsbusiness logic and the other type is more inclined towards UI. 

  • Presentational Component: React components which decide the look and feel of UI are called presentational component. These components can be stateful or stateless components. State of these components are normally UI level state instead of application (business logic) state. These components are reusable and often used to have independent styles. For example: above Greeting component is a presentational component which can we be reused multiple places in application. 

  • Container Component: React component which mainly deals with application level state, rarely contains HTML tags and interact with API data are known as container component. This categorisation is basically separation of UI logic and application logic.

Component and its lifecycle 

In React JS, class-based components are extended from React.Component class which provides several lifecycle methods to component. render is also a life cycle method which must be implemented in React component. Other lifecycle methods are optional and can be used to gain more control over the React component. As ReactJS has evolved with time, few lifecycle methods are no longer supported and will be removed from library in coming update. In this article, we will look into the lifecycle methods which are supported by library version 16.4+.  

React lifecycle

React lifecycle. 

To understand component's lifecycle methods and their invocation orders, we can divide all the methods in three broad category: Mounting, Updating, Unmounting 

  • Mounting: When component mounts then first of all constructor method (if present) is called. constructor method takes props as argument and pass props to the constructor method of React.Component class. Refer the example of class based component above. then getDerivedStateFromPropsstatic method will be invoked. getDerivedStateFromPropstakes two argument - props and state and returnsan object to update the state or returnsnull to update nothing. This lifecycle method is used when the state is dependson props. After getDerivedStateFromPropsmethod, render method is being called which returns the JSX. After render, componentDidMount is called which is the last method in mounting phase. We normally put API calls in componentDidMount lifecycle method. To summaries the mounting of component:

  • constructor 

constructor(props) { 
super(props); 
// code here 
}
  • getDerivedState From Props 

static getDerivedStateFromProps(props, state) { 
// code here 
// return updated state object or null 
} 
  • render 

render() { 
// code here 
} 
  • componentDidMount 

componentDidMount() { 
// code here 
} 
  • Updating:  After a component is mounted, A React component is changed either when the state of component or props passed is changed. on update, first getDerivedStateFromPropsstatic method is called which returns the object to update the state or return null to update nothing. Then shouldComponentUpdate lifecycle method is called which takes two arguments (nextProps and nextState) and return a boolean. This method decides whether render method should be invoked or not. If this method returnstrue then render method will be invoked otherwise component will not get updated. This method is used to optimise the React component by reducing the number of re-renders. if shouldComponentUpdate return true (which is also the default return value of method) then render method will be invoked which updated the component based on updated state or new props. After render method getSnapshotBeforeUpdate method is called. this method is invoked right before the rendered output is committed to DOM. It takes two arguments prevProps and prevState. this method gives access to DOM before React is going to update it with recent changes. For example, you can access last scroll position before update (re-render). Value returned by getSnapshotBeforeUpdate will be passed to componentDidUpdate method which is the next lifecycle method invoked. componentDidUpdate is called right after update occurs. This method takes three arguments prevProps, prevState and snapshot. last argument snapshot will be the value returned from getSnapshotBeforeUpdate lifecycle method. To summarise update phase of component:
  • getDerivedState From Props 

static getDerivedStateFromProps(props, state) { 
// code here 
// returns updated state object or null 
} 
  • should Component Update 

shouldComponentUpdate(prevPropsprevState) { 
// code here 
// returns true to re-render the component otherwise return false.  
// default is true 
} 
  • render 

render() { 
// code here 
} 
  • getSnapshot Before Update 

getSnapshotBeforeUpdate(prevPropsprevState) { 
// code here 
} 
  • component Did Update 

componentDidUpdate(prevPropspreState, snapshot) { 
// code here 
} 
  • Unmounting: Last phase of React component is unmount. it invokes the last method of React component's lifecycle componentWillUnmount. this method is called before the component is unmounted and destroyed. Normally, clean up code is put in componentWillUnmount method. we should not call setState method here as component is never going to be re-rendered after unmount. To summarise:

componentWillUnmount 
componentWillUnmount() { 
// code here 
}

Set up a React project 

As JavaScript has evolved and tooling has become an essential part of web development. There are many approaches to start a React project but the most popular one is create-react-app (popularly known as CRA). create-react-app is available as NPM module which means to use CRA, one must have NodeJS and NPM installed on machine. 

Create React project with CRA 

First check the NodeJS and NPM installation on machine by executing following command: 

node --version 
npm --version 
npx –version 

In case NodeJS is not install then download and install it from. 

Once it is confirmed that NodeJS and NPM is installed on system then execute following command to create a React project: 

npx create-react-app My First React Project 

NPX command comes with NPM. It is used to use any NPM without actually installing the NPM. above command will create a new React project with latest version of create-react-app in your current directory. Execute following command to run the project: 

cd My First React Project 

npm start 

This would start a local server at port number 3000 and open default React page in browser.

React page in browser

Understanding project generated by CRA project generated by CRA

Above image shows the files and folder generated by CRA. let us go through it and understand: 

  • package.json: This file contains NPM dependencies, NPM scripts, project name, version etc... 
  • public folder: All public assets will be present in public folder like index.html, image or logo etc... 
  • src folder: All our JS code including React components will be present in src folder. 

CRA configured our React project with all the needed tooling required for web development. It configured Webpackdev server with hot reload ( on file save browser reloads the page to reflect latest change), Eslintreact-testing-library for unit testing React components etc... 

src/index.js is the starting point of our React project. Project also has one sample React component App.js. You can make changes to App.js and it will be reflected on browser. 

What type of React Component should I build in 2020 

So far, we have learnt different ways of writing React component. Now it is time to choose which pattern should you choose for writing React components. As we have discussed in previous article that ReactJS is moving towards functional programming paradigm and with the introduction of hooks in version 16.8, Writing functional component fulfils most of our use cases.

Let's create our first stateful functional component. We will be building a simple counter component. The final output looks like this: 

Counter component code: 

import React, { useState } from "react"; 
import "./Counter.css"; 
function Counter() { 
const [count, setCount] = useState(0); 
const increment = () => { 
const updatedCount = count + 1; 
setCount(updatedCount); 
}; 
const decrement = () => { 
const updatedCount = count - 1; 
setCount(updatedCount); 
}; 
return ( 
<div className="counterContainer"> 
<button type="button" onClick={decrement}> 
-
</button> 
<span>{count}</span> 
<button type="button" onClick={increment}> 
+ 
</button> 
</div> 
); 
} 

export default Counter; 

Styles are added in Counter.css 

.counterContainer { 
background-color: #fff; 
font-size: 24px; 
font-weight: 500; 
border: 1px solid #0874ce; 
border-radius: 3px; 
box-shadow: 1px 1px 4px 0 #0084ff; 
} 
.counterContainer button { 
outline: none; 
border: none; 
width: 50px; 
height: 40px; 
background-color: transparent; 
font-size: 24px; 
font-weight: 500; 
cursor: pointer; 
} 
.counterContainer span { 
color: #0084ff; 
} 

We have created a fully functional counter component which can be used anywhere in React application.

KnowledgeHut

KnowledgeHut

Author

KnowledgeHut is an outcome-focused global ed-tech company. We help organizations and professionals unlock excellence through skills development. We offer training solutions under the people and process, data science, full-stack development, cybersecurity, future technologies and digital transformation verticals.
Website : https://www.knowledgehut.com

Join the Discussion

Your email address will not be published. Required fields are marked *

Suggested Blogs

How to Create a Collection in MongoDB?

In recent years, MongoDB has retained its top spot among NoSQL databases. The term NoSQL means non-relational. Mongo is an open-source document-oriented, NoSQL Database that allows users to query data without having to know SQL. You can read more about MongoDB here.MongoDB stores data in the form of collections. In this blog we will learn how to create a collection in MongoDB.PrerequisitesTo follow this blog, you should be having the latest version of MongoDB installed in your machine. You can download MongoDB for your operating system from this link.Let’s start by understanding the term collection.What is a collection in MongoDB?We all know that MongoDB stores data in the form of documents. All the similar documents are stored in a collection. It is same as a Table in a SQL database or any of the Relational Databases.An example of a collection is shown below:Source: mongodb websiteEach object in MongoDB is called a document. All the objects put together create a collection.Creating a Collection in MongoDBHow to create a collection in MongoDB?There are a couple of methods to create a collection in MongoDB:The createCollection() MethodCreating the Collection in MongoDB on the flyLet’s have a look at each of the methods one by one.To start with we need a mongo server in our local machine. To do that, open the terminal for Mac and Linux, and PowerShell or command prompt for Windows. Run the following command.Command: mongodThis fires up the MongoDB server.  To run the MongoDB commands, we need to start a MongoDB shell. For this, open a new window in terminal or PowerShell or command prompt and run the following. We shall refer to this window as mongo shell in the rest of this article.Command: mongoThis creates a shell where we can run MongoDB commands.Let's create a database and use it so that we can test our examples. For doing the same, run the following command in the mongo shell.Command: use myDBThis creates a new database with the name myDB and switches to that database, so that we can work with it.The createCollection() Method:Using createCollection method we can create a collection which does not have any documents or an empty collection. The syntax of createCollection() command is as follows: Syntax: db.createCollection(name, options)The createCollection method takes 2 parameters, the first parameter is the name of the collection which is a string and the other is an options object which is used to configure the collection. The options object is optional.   To create the collection without passing the options using createCollection method, run the following command in the mongo shell. Command: db.createCollection("testCollection")This creates a collection with the name testCollection inside myDB database.To see the collection, run the following command inside the mongo shell.Command: show collectionsThis should show all the collections we have inside the database.We can add additional configurations to the collection. For example, we can add validation or create a capped collection using the second parameter which is the options object.Configuration options for creating a collection in MongoDBThe basic syntax for configuring an object in createCollection method is as shown below.Syntax:db.createCollection( ,    {      capped: ,      autoIndexId: ,      size: ,      max: ,      storageEngine: ,      validator: ,      validationLevel: ,      validationAction: ,      indexOptionDefaults: ,      viewOn: ,              // Added in MongoDB 3.4      pipeline: ,          // Added in MongoDB 3.4      collation: ,         // Added in MongoDB 3.4      writeConcern:    } ) Let’s look at all the options in detail.FieldTypeDescriptioncappedboolean(Optional). To create a capped collection, specify true. If you specify true, you must also set a maximum size in the size field.autoIndexIdboolean(Optional). Specify false to disable the automatic creation of an index on the _id field.sizenumberOptional. Specify a maximum size in bytes for a capped collection. Once a capped collection reaches its maximum size, MongoDB removes the older documents to make space for the new documents. The size field is required for capped collections and ignored for other collections.maxnumberOptional. The maximum number of documents allowed in the capped collection. The size limit takes precedence over this limit. If a capped collection reaches the size limit before it reaches the maximum number of documents, MongoDB removes old documents. If you prefer to use the max limit, ensure that the size limit, which is required for a capped collection, is sufficient to contain the maximum number of documents.storageEnginedocumentOptional. Available for the WiredTiger storage engine only.Allows users to specify configuration to the storage engine on a per-collection basis when creating a collection.validatordocumentOptional. Allows users to specify validation rules or expressions for the collection.validationLevelstringOptional. Determines how strictly MongoDB applies the validation rules to existing documents during an update.validationActionstringOptional. Determines whether to create an error on invalid documents or just warn about the violations and allow invalid documents to be inserted.indexOptionDefaultsdocumentOptional. Allows users to specify a default configuration for indexes when creating a collection.viewOnstringThe name of the source collection or view from which to create the view. The name is not the full namespace of the collection or view; i.e. does not include the database name and implies the same database as the view to create. You must create views in the same database as the source collection.pipelinearrayAn array that consists of the aggregation pipeline stage(s).creates the view by applying the specified pipeline to the viewOn collection or view.collationdocumentSpecifies the default collation for the collection.Collation allows users to specify language-specific rules for string comparison, such as rules for lettercase and accent marks.writeConcerndocumentOptional. A document that expresses the write concern for the operation. Omit to use the default write concern.To know more about the options go to this link.Example of Create Collection in MongoDBAn example for creating a collection with the options before inserting documents is shown below. Run the below command in the mongo shell.Command: db.createCollection("anotherCollection", { capped : true, autoIndexID : true, size : 6142800, max : 10000 } )This creates a capped collection.What is a capped collection?A fixed-sized collection that automatically overwrites its oldest entries when it reaches its maximum size. The MongoDB oplog that is used in replication is a capped collection.See more about capped collection and oplog over here.Create a Collection with Document ValidationMongoDB has the capability to perform schema validation during updates and insertions. In other words, we can validate each document before updating or inserting the new documents into the collection.To specify the validation rules for a collection we need to use db.createCollection() with the validator option.MongoDB supports JSON Schema validation. To specify JSON Schema validation, use the $jsonSchema operator in your validator expression. This is the recommended way to perform validation in MongoDB.What is $jsonSchema?The $jsonSchema operator matches documents that satisfy the specified JSON Schema. It has the following syntax.Syntax: { $jsonSchema: }The example for json Schema object is given below.  Example:  {   $jsonSchema: {      required: [ "name", "year", "skills", "address" ],      properties: {         name: {            bsonType: "string",            description: "must be a string and is required"         },         address: {            bsonType: "object",            required: [ "zipcode" ],            properties: {                "street": { bsonType: "string" },                "zipcode": { bsonType: "string" }            }         }      }   } }To create a collection with validation rules, run the below command in the mongo shell.Command:db.createCollection("employees", {    validator: {       $jsonSchema: {          bsonType: "object",          required: [ "name", "year", "skills", "address" ],          properties: {             name: {                bsonType: "string",                description: "must be a string and is required"             },             year: {                bsonType: "int",                minimum: 2017,                maximum: 2021,                description: "must be an integer in [ 2017, 2021] and is required"             },             skills: {                enum: [ "JavaScript", "React", "Mongodb", null ],                description: "can only be one of the enum values and is required"             },             salary: {                bsonType: [ "double" ],                description: "must be a double if the field exists"             },             address: {                bsonType: "object",                required: [ "city" ],                properties: {                   street: {                      bsonType: "string",                      description: "must be a string if the field exists"                   },                   city: {                      bsonType: "string",                      description: "must be a string and is required"                   }                }             }          }       }    } })This creates a collection with validation.Now if you run show collections command, employees collection should show up.Now, let’s look at the second method that is “Creating the Collection in MongoDB on the fly”Creating the Collection in MongoDB on the flyOne of the best things about MongoDB is that you need not create a collection before you insert a document in it. We can insert a document in the collection and MongoDB creates a collection on the fly. Use the below syntax to create a collection on the fly.Syntax: db.collection_name.insert({key:value, key:value…})Now let’s create a collection on the fly. To achieve that, run the following command in the mongo shell.Command:db.students.insert({ name: "Sai",   age: 18,   class: 10 })This creates a collection with the name students in the database. To confirm, you can run show collections command and check. This should show all the collections which have students collection, as shown in the following image.To check whether the document is successfully inserted, run the below command in the mongoshell to check.Syntax: db.collection_name.find()Command: db.students.find()This should show all the documents inside the collection.ConclusionIn this blog you have seen how to create a collection in MongoDB using different methods, along with examples.  MongoDB is a rapidly growing technology nowadays as it is flexible, fast and for many more reasons. Many companies are using MongoDB as their go-to database of choice. Learning MongoDB is recommended by many of the web developers as it boosts the probability of getting a job as well.
3467
How to Create a Collection in MongoDB?

In recent years, MongoDB has retained its top spot... Read More

How to Install MongoDB on Windows 10

Conventional relational database management systems make it tough to scale data warehousing, grid, web 2.0, and cloud applications. Their non-linear question execution time, unstable question plans, and static schemas are a huge disadvantage and make data management a strenuous task. As a result, the servers fail to update and retrieve data as per expectations. MongoDB, a document-oriented database server, solves all these problems by offering unbeatable service at speeds that modern technologies demand.MongoDB is a popular distributed database that supports replication, horizontal partitioning (sharding), a flexible document schema, and ACID guaranteed on the document level. Moreover, the support for Ad-Hoc queries, flexibilities, auto sharding and auto-failover, schema-free migration, effective horizontal scalability, and access to professional technical support makes the database the most favourite among programmers worldwide.PrerequisitesTo download and install MongoDB successfully on your computer, you must have the minimum requirements to avoid errors in your installation process.The hardware and the software requirements you need for installing MongoDB are stated below:Hardware requirementsRAM 4GB   CPU Intel Core i3TM i3 HQ CPU @2.50 GHz ROM 256 GBSoftware requirementsAny browser like Google Chrome, Mozilla Firefox, or Microsoft Edge.Installation ProcedureLet us look at the step-by-step approach on how to install, set-up, and configure MongoDB in Windows 10.Step-1: Download the installer.Download MongoDB Community (.msi) file installer from the link below:Now go to the official MongoDB site and click on Community Server as shown:In the Version dropdown, select the version of MongoDB to download as shown:a. In the Platform dropdown, select Windows.b. In the Package dropdown, select msi. (Mark it as the most crucial step.)c. Click Download.Based on your internet speed, the MongoDB msi installer may take time to download in your system.Once you have successfully downloaded MongoDB on your system, it's time to specify where you want to store the set-up code. Specify the location you want to keep the MongoDB Windows installer package. For example, here we are storing the package in the Local Disc (F:) in our system.Step-2: Run the MongoDB installer.Now, its time to run the application in your system. Run the application by following the simple steps:a. Go to the directory where you downloaded the MongoDB installer (.msi file). By default, this is your Downloads directory.b. Double-click the .msi file.Step-3: Click on NextYou will get a welcome message from the MongoDB Community Edition installation wizard. The set-up wizard will guide you through the installation of MongoDB in your system. To continue with the installation process, click on Next.Step-4: Read the End-User License AgreementAdhere to the terms of using the software. Read the end-user license agreement carefully before proceeding further.Step-5: Accept the termsOnce you have read the terms and conditions mentioned by the MongoDB community, click on the square box as shown below. Further, click on the Next button to continue.Step-6: Choose Setup Type – CompleteOnce you land on the choose set-up type page, choose the option as Complete and then click the Next button.Attention: MongoDB allows you to choose either the Complete (recommended for most users) or Custom (to customize the set-up type you desire) buttons.Step-7: Keep Service Configuration as default.N.B.: Don’t make any changes here and keep all these parameters as default. Click on the Next button.Data directory: Select the data directory, which leads you to the --dbpath. In case this directory does not exist, the installer will create the directory automatically and set the directory access to the service user.Log Directory: Select the Log directory, which is similar to the --log path. If the directory does not exist, the installer will create the directory automatically and set the directory access to the service user. All this is done automatically.Install MongoDB as a Service.Service Name: MongoDBData Directory: C:\Program Files\MongoDB\Server\4.4\data\Log Directory: C:\Program Files\MongoDB\Server\4.4\logAttention: Note that if you already have a customized name service, you must choose another name.Run the service as a local or domain user.For an existing local user account, specify a period (i.e..) for the Account Domain and specify the Account Name and the Account Password for the user.For an existing domain user, specify the Account Domain, the Account Name, and the Account Password for that user.Step-8: In the next step you will get an option to install MongoDB compass. Ignore and click on the Next button.Step-9: Click on InstallOnce you land on the Ready to Install MongoDB page, click on Install as shown below. Once done, the MongoDB installation begins.The installation now starts. Based on your system speed, the installation may take a few minutes, and you are expected to get an image as shown:Step-10: Click the Finish button.The finish button will exit the Setup Wizard. On clicking the finish button, the installation gets completed.Congratulations! You have successfully installed MongoDB and set up MongoDB in your local system.What’s Next?Go to file location of MongoDB and copy the path of MongoDB bin directory as shown below:Open Windows Command PromptRun as administratorNow type cd to change the directory path to the desired path as shown below:cd c:\Program Files\MongoDB\Server\4.4After typing mongo, press enter. You will get to see the image below:To check the databases, type show databases as shown below:If you want to know the admin, type use admin as shown below:To check the collection in the database, type show collections as shown below:Checking the VersionOnce you have downloaded MongoDB in your system, use the below command to check the version of MongoDB installed in your system.Attention: You may have noticed that we have not yet specified the path for our environment variable, which is why we have to manually type C:\Program Files\MongoDB\Server\4.4 to run MongoDB in our system.Setting the path to Environmental VariableStep-1: Go to my computer, right-click and choose the option as properties.Step-2: Choose the advanced system settings option in the top left as shown:Step-3: Now go to Environment variables as shown below:Step-4: Go to system variables and choose the option path as shown below:Step-5: Add the C:\Program Files\MongoDB\Server\4.4 and press OK.Now you can see, we are able to run MongoDB without bringing the C:\Program Files\MongoDB\Server\4.4Creating a demo database:Till now we have seen how to set up and install MongoDB in our system. Now let us see a demo on how to create a database in MongoDB.Step-1: Go to the command prompt and type mongo.Step-2: After opening MongoDB prompt, create a new database with the name KnowledgeHut Global using the following command:Use KnowledgeHut Global and add data into the collection.Step-3: Showing database in the collectionshow collections;Uninstallation ProcedureLet us see how to uninstall MongoDB from the system. To uninstall MongoDB from our system, we need to follow the following steps as discussed below:Step-1: Go to the control panel.Step-2: Choose the option: Uninstall a program.Step-3: Select MongoDB from the list.Step-4: Right Click on MongoDB and you will find three options as shown below:Step-5: Click on uninstall and complete the uninstallation process.That’s all! You will have successfully uninstalled MongoDB from Windows 10.Let’s Verify:Go to your Windows command prompt and run the command to check the version of MongoDB in your system.mongod --versionYou will get an error message because you have uninstalled MongoDB from the system.ConclusionMongoDB has unparalleled and unique advantages over SQL-based databases because it allows data replication to mirror servers with full flexibility and reliability. Plus, the installation process is not complicated and can be completed with ease by following the step-by-step instructions mentioned above.   Just keep in mind that the MongoDB installers come in both 32-bit and 64-bit format. Based on your work requirement and your system configuration, choose the format to cater to your database needs. If your work involves more testing and development, then a 32-bit installer is definitely recommended. However, the 32-bit installer is not a perfect choice for production environments as this type of format limits the amount of data stored in the database. Perhaps, you must opt for a 64-bit installer in your system to get the most of MongoDB.
3444
How to Install MongoDB on Windows 10

Conventional relational database management system... Read More

The 2021 Learning Path To Becoming a Full Stack Web Developer

Full stack developer roles are among the hottest careers in the tech space now. These talented folks can develop a whole product from scratch. A full stack developer is a combination of Front-end developer and Backend developer. These two in themselves are full time jobs and most people make careers out of one of them. So, we will start with Front-end roadmap and then go to Back-end roadmap. A person interested in becoming a Full-stack developer needs to have proficiency in both the front end and back-end tools, just like I started as a Front-end developer and later on become a Full stack developer by mastering JavaScript backend technologies and databases.The demand for Full Stack Web DeveloperThe demand for Full stack developers is the highest in early-stage startups, where they want to create a Minimum Viable Product at the earliest to showcase to the investors. It is also a nice skill to have in addition to frontend technologies or backend technologies alone, since an employer prefers people with both skills.There are a lot of technologies to learn to be a Full-Stack developer. We will discuss about them in the coming sections.   List of technologies to master to become a Full-Stack developer A full-stack developer is actually a combination of Frontend developer and Backend developer. We need to master both, and both have different Roadmaps. Let’s start with the basics. The frontend is the web-site which we see and it is primarily made with HTML and CSS.  JavaScript was also used earlier but nowadays, it is created with JavaScript frameworks like ReactJS, Angular or Vue. All these frameworks require one to learn the basics of HTML, CSS, & JavaScript. So, we need to learn the basics followed by at least one framework.In the backend we have a lot of technologies and databases also. So, we need to choose one backend framework from Java (Spring Framework), JavaScript (NodeJS) etc and then also learn databases. Databases are divided into two categories, which is NoSQL(MongoDB) and SQL(PostgreSQL, MySQL, Oracle) databases. So, you need to choose one of the databases.We are also required to know about DevOps, which is a practice of harmonizing development and operations whereby the entire pipeline from development, testing, deployment, continuous integration and feedback is automated. The knowledge of either AWS or Azure based cloud ecosystem is required, and also CI/CD like Jenkins and containerizing & orchestrating applications using Docker and Kubernetes.1. Frontend RoadmapLearn the BasicsPlease refer to the attached figure for Front-end roadmap, as we will be referring to this throughout this article. We have to start our journey by learning HTML, CSS and JavaScript which is the base for a web-app or website. HTML has changed a bit over the years, with the introduction of HTML 5 and semantics tags, so make sure to update yourself. JavaScript which was released in 1995, didn’t change much during the next 20 years. But once more and more developers started using it, the ECMA committee decided to add some very nice features and enhance the language, and renamed it ES6 in 2015. After that they regularly added new features to the language and have just released ES2020 in June 2020, which has many additional features. So, learn the basic JavaScript first and then upgrade to ES6 and newer versions. CSS is what makes a website or web-app beautiful, and is often considered the hardest part by a developer. Earlier, CSS was very confusing and had a steep learning curve, because of the use of floats to create a layout. Developers usually used to work with CSS frameworks like bootstrap to design a site. But things have changed a lot with the invention of CSS Grid and Flexbox. Some of the best resources to learn the basics are - html.specdeveloper.mozilla.HTMLStyle CSSdeveloper.mozilla.CSSdeveloper.mozilla.JavaScriptGetting Deeper Now, just learning JavaScript and some basic CSS will not make you a good Front-end developer as you have to take a deep dive into JavaScript. We will discuss CSS later, after learning the essentials of JavaScript.JavaScript EssentialsThere are many things associated with JavaScript which we need to learn before moving forward.The Terminal The first thing to learn is to work in a terminal, and master some of the basic commands. If you are on a Mac, it’s already based on Linux and runs most Linux commands. If you are working on Windows then you must install git bash, which will give you a Linux environment to work with. In JavaScript frameworks, we need to run a lot of commands from the terminal, like if we want to install a third-party dependency by npm.  The basics of Linux can be learnt from their official site.Version ControlNext, learning version control is very important because we should always keep our code in some remote repository like Github. The industry works on Git, which is version control software. It is completely command-based and is used heavily everywhere. Learn the basic commands which will be useful even for an individual developer. Later on, when working with teams, more advanced knowledge of the git command is required.Through the git commands, we store our code in repositories. The most popular ones are Github and Bit Bucket, so we need to learn how to store and link them.The basics of git can be learnt from this awesome tutorial.freecodecamp.orgTask Runners Task runners are applications which are used to automate tasks required in projects. These tasks include minification of JavaScript and CSS files, CSS preprocessing like from SASS to CSS, image optimization and Unit testing. The three popular task runners are npm scripts, gulp and grunt. The npm script is nothing but the package.json file which comes with React projects or is created in a Node.js project using npm init. Gulp and Grunt are much bigger applications and also have a plugin ecosystem that is suited for large JavaScript projects. The basics for these two technologies can be learnt from here. Module Loader and Bundler Both module loaders and bundlers are required for large JavaScript applications. Knowledge of both is required, if the project you are working is a big Vanilla JavaScript project. When a large JavaScript application consists of hundreds of files, the module loader takes care of the dependency and makes sure all the modules are loaded when the application is executed. Examples are RequireJS and SystemJS.Module bundlers also do the same thing, building it at the time of application build rather than at the runtime. Popular examples are Webpack and Rollup. Testing Testing nowadays is very important in any type of project. There are two types of testing; one is known as Unit testing and other as end-to-end testing. For unit testing we write test cases and the most popular tool nowadays is Jest. End-to-end testing is automated testing, which emulates the whole app. Suppose, an app has a login screen and then it shows posts. The testing tool will run the web-app to check whether all the functionalities are done correctly. The two most popular options today are Puppeteer and Cypress. The tutorials to refer for these topics are - Libraries and FrameworkThey are the most important part of the JavaScript ecosystem nowadays. It all started with the release of AngularJS in 2010. Before that period most enterprise apps were made in Java and were desktop apps. But AngularJS changed everything, because it made it easy to manage big projects with JavaScript and helped to create complex web-apps.1. React It is the most popular JavaScript library today and is used by both enterprises and startups that have a huge ecosystem. It is not a complete framework like Angular and we have to install third party dependencies for most things. But if you want to learn a framework that will get you a job, then that framework would be ReactJS, and its demand is not going away for the next 5 years. The component approach and its easy learning curve have made React more popular than other frameworks. A good starting tutorial for React isState Management In React state management can sometimes become complex, when we need to share data between components. We generally take help of external packages in it with the most popular being Redux. But we also have other state management libraries like XState and Recoil. Server-side rendering With performance becoming important nowadays, Server-Side Rendering speeds up the React projects even faster. In SSR projects, the React code is rendered on the server and the client browser directly receives the HTML, CSS, JS bundle. The only framework to do it is NextJS. Static Site Generators Lot of sites don’t need to be updated frequently and it is the place where the only Static Site Generator for ReactJS, which is GatsbyJS shines. With the help of GatsbyJS we can create extremely fast static sites and it gets into Wordpress domain a lot with it. GatsbyJS also has a huge ecosystem of plugins, which enhances its functionalities. React Testing Unit testing is a very important part of ReactJS projects, especially the ones which are very large. Unit testing ensures that we have lower bugs in Production build. The two popular libraries are – Enzyme and Jest. 2. Angular It is a complete framework and unlike React requires very few external dependencies. Everything is built within Angular and we don’t have to go outside for more features. Since it was among the earliest frameworks, older projects are in Angular and it is still widely used in enterprises. A good tutorial to learn Angular is below. 3. Vue Vue is another very popular JavaScript library, which has the best features of both ReactJS and Angular and has become very popular in recent years. It is widely used in both enterprise and startups. A good tutorial to start with Vue is below. 4. NuxtJS It is used for Server-Side Rendering in Vue projects and is similar to the NextJS framework used in ReactJS for SSR.  5. Svelte It is the newest of all frameworks/libraries and has become quite popular, but still not used much in enterprises and startups. It is different from React, Vue and Angular and converts the app at build time rather than at run time as in the other three. Good tutorials to start with Svelte are below. CSS Deep DiveA lot has changed in CSS after it included CSS Grid and Flexbox; it has become much easier for developers to work with. CSS Essentials It is now mandatory for frontend developers to learn CSS Grid and Flexbox, because through it we can develop beautiful layouts with ease. More companies are moving away from CSS Frameworks and have started working with CSS Grid and Flexbox, which are now supported by all browsers. Good tutorials to learn Flexbox and CSS Grid are below. Preprocessors CSS preprocessors are used to add special functionalities in CSS, which it lacks. An example is Sass, which adds special features like variables and nested rules in CSS and is widely used in the industry for larger projects. The other popular one is PostCSS, in which we can use custom plugin and tools in CSS. CSS Frameworks Frameworks were very popular from the early days of CSS, when it was very complicated because of floats. Bootstrap This is the most popular and oldest CSS framework; easy to learn and also has a wide variety of elements, templates and interfaces. Bulma It is another CSS framework, which is very popular and much easier to use than bootstrap. Tailwind CSS This is a fairly new CSS framework and is quite popular nowadays. It follows a different approach than the other frameworks and contains easier classes. Styled Components (React) This is a CSS in JS library and is for React only. It is used to create components out of every style and is very popular in the React world.  CI/CDThe Continuous Integration/ Continuous deployment is mainly used by DevOps. But a frontend engineer should know its basics. It is used to build, test and deploy applications automatically.Github Actions  It is a freely available CI/CD pipeline, which directly integrates to your github based project and can be used in a variety of languages. Deployment It is again a task which mainly falls into the domain of Backend engineers and DevOps, but a frontend engineer should know some basic and simple tools. Static Deployment These products are mainly used to deploy static sites, which consists of HTML, CSS and JavaScript only. Two very popular services are Amazon S3 and Surge.sh Node Application Deployment The projects containing node code cannot be deployed using static deployment. Even if the project is a simple ReactJS project, it also uses node for processing. These applications require services which run the Node code and deploy it. The three most popular services are Vercel, Firebase and Netlify. 2. Backend Roadmap (Including Storage, Services & Deployment)Understanding the BackendBackend is the part of the website that provides the functionality, allowing people to browse their favorite site, purchase a product and log into their account, for instance. All data related to a user or a product or anything else are generally stored in databases or CMS (Content Management System) and when a user visits any website, they are retrieved from there and shown. One of the responsibilities of a backend engineer involves writing APIs, which actually interact with the database and get the data. They are also involved in writing schemas of database and creating the structure of databases. Backend EssentialsFor a backend engineer, working in a Linux environment is an essential skill. A lot of the configurations are done on the terminal. So, he or she should be very good with Linux commands.Also, they should know both commands and the use of any git powered platforms like Github or bitbucket.Languages and FrameworksAll of the popular languages have some framework, which has been used for backend development. These frameworks are generally used to create API endpoints, which are used to fetch or store data in the database. For example, when we scroll articles on Facebook, these articles are fetched from a database and we use the GET method to fetch them. Similarly, when we write an article and hit submit, it uses POST method.Now, different frameworks implement this GET, POST and other APIs also referred to as RESTful APIs in their own way.Java Java is by far the oldest and the most used language for backend development. It is also used for a variety of other tasks like Android development, but it shines in the backend because of its multithreading abilities. So, enterprise grade web-apps and web-apps with a lot of traffic prefer Java, because it handles loads better. The most popular frameworks for backend development in Java are Spring Framework and Hibernate. Some good beginner's tutorials are - JavaScript It is a very popular choice for backend development, because on the frontend side JavaScript is the only choice. So, a lot of frontend engineers can take this choice to become Full-stack developers. Node.js It allows developers to use JavaScript to write server-side code, through which they can write APIs. Actually, the API part can be done by numerous frameworks of Node.js out of which Express is widely used. The other popular framework is Fastify. Some good beginner's tutorials are - Python Python is one of the most popular languages among developers and has been used in a variety of fields. The two most popular frameworks for Python are Flask and Django. Some good beginner tutorials are - C# It is a very popular programming language which was developed by Microsoft and it has the power of C++. Its popularity increased once the .NET framework was released for backend development. As Microsoft is very popular in enterprises, the .NET framework is generally preferred in enterprises. A good tutorial to learn .NET is - Go Go language which is also referred to as Golang, has gained popularity in recent years. It is used a lot in Backend programming and the two popular frameworks are Gin and Beego. DatabaseFor a Backend engineer, after making APIs with framework based on language, it's time to learn about Databases. Databases are used to store most of the things which we see in a web-app, from user login credentials to user posts and everything else. In the earlier days we only used to have one type of Database and that was Relational databases, which use tables to store data. Now we have two other categories also, one being NoSQL databases and the other In-memory databases. 1. Relational databases Relational databases allow you to create, update and delete data stored in a table format. This type of database mostly uses SQL language to access the data, hence is also known as an SQL database. MySQL It is one of the oldest databases and was released in 1995. It is an open-source database and was very popular in the 2000s with the rise of LAMP (Linux, Apache, MySQL, PHP) stack. It is still widely in use, but there are other popular Relational databases. A good tutorial to learn MySQL is - PostgreSQL PostgreSQL, which is also known as Postgres is also an old open-source Relational database, which was released in 1996. But it gained popularity recently, as it goes very well with modern stacks containing NodeJS and other backend technologies. A good tutorial to learn PostgreSQL is - Oracle is the most popular and oldest relational database. It was released in 1979 and still remains the number one preference for enterprise customers. All the big banks and other organizations, run on Oracle databases. So, the knowledge of Oracle is a must in many companies for an Engineer. A good tutorial to learn Oracle is - MS-SQL MS-SQL is also known as Microsoft SQL and is yet another commercial Relational database. It has got different editions, used by different audiences. It is also heavily used by enterprise users and powers a whole lot of big systems around the world. A good tutorial to learn MS-SQL is - 2. NoSQL databases NoSQL databases are also called non-SQL databases. The NoSQL databases mainly store data as key-value pairs, but some of them also use a SQL-like structure. These databases have become hugely popular in the 21st century, with the rise of large web-apps which have a lot of concurrent users. These databases can take huge loads, even millions of data connections, required by web-apps like Facebook, Amazon and others. Beside this, it is very easy to horizontally scale  a NoSQL database by adding more clusters, which is a problem in Relational Databases. MongoDB It is the most popular NoSQL database, used by almost every modern app. It is a free to use database, but the hosting is charged if we host on popular cloud services like MongoDB atlas. Its knowledge is a must for backend engineers, who work on the modern stack. MongoDB uses json like documents to store data. A good tutorial to learn MongoDB is - It is a proprietary database service provided by Amazon. It is quite similar to MongoDB and uses key-value pairs to store data. It is also a part of the popular AWS services. A good tutorial to learn DynamoDB is-Cassandra is an open-source and free to use NoSQL database . It takes a different approach when compared to other NoSQL databases, because we use commands like SQL, which are known as CQL (Cassandra Query Language). A good tutorial to learn Cassandra is - 3. In-memory databases The in-memory database is a database, which keeps all of the data in the RAM. This means it is the fastest among all databases.  The most popular and widely used in-memory database is Redis. Redis Redis (Remote Dictionary Server) is an in-memory database, which stores data in RAM in a json like key-value format. It keeps the data persistent by updating everything in the transaction log, because when systems are shut down their RAM is wiped clean. A good tutorial to learn Redis - StorageStoring the data is an important part of any application. Although this is mainly DevOps territory, every backend developer should know the basics for the same. We need to store the database data and also the backend code. Beside this the frontend code must also be stored somewhere. Nowadays everything is stored in the cloud, which is preferred by individuals, startups and enterprises. The two most popular cloud-based storages are – Amazon S3 Azure Blob Storage Good beginner's tutorials for both areServices and APIsThese are theoretical concepts and are implemented by various services, but a backend engineer should know them and how to use them. Restful APIs This is by far the most popular way to get data from a database. It was made more popular, with the rise of web-apps. We do GET, PUT, POST and DELETE operations to read, update, create or delete data from databases. We have earlier discussed different languages and frameworks, which have their own implementations for these operations. Microservices Architecture In microservice architecture, we divide a large and complex project into small, independent services. Each of these is responsible for a specific task and communicates with other services through simple APIs. Each service is built by a small team from the beginning, and separated by boundaries which make it easier to scale up the development effort if needed. GraphQL It is the hottest new kid in the block, which is an alternative to the Restful APIs. The problem with Restful APIs is that if you want some data stored in database, you need to get the whole data sent by the endpoint. On the other hand, with GraphQL, you get a query type language which can return only the part of the data which you require.  DevOps & DeploymentA backend engineer requires a fair bit of DevOps knowledge. So, we will next deep dive into the methodologies in DevOps. 1. Containerization & Orchestration Containers are a method of building, packaging and deploying software. They are similar to but not the same thing as virtual machines (VMs). One of the primary differences is that containers are isolated or abstracted away from the underlying operating system and infrastructure that they run on. In the simplest terms, a container includes both an application’s code and everything that code needs to run properly. Container orchestration is the automatic process of managing the work of individual containers for applications based on microservice architecture. The popular Containerization and Orchestration tools are – Kubernetes Docker Good beginner's tutorials for both are -2. DevOps DevOps is a set of practices that combine software development (Dev) and IT operations (Ops). It aims to shorten the systems development life cycle and provide continuous delivery with high software quality. The two most popular DevOps services are AWS and Azure. Both of them are cloud based and are market leaders. Both of these platforms contain a wide variety of similar services. AWS It consists of over 200 products and services for storage, database, analytics, deployment, serverless function and many more. AWS is the market leader as of now with 33% of market share. The AWS certifications are also one of the most in-demand certifications and a must for frontend engineers as well as Backend engineers. Azure Microsoft Azure is second in terms of market share of cloud-based platforms, with 18% of the market. It also consists of SaaS (Software as a Service), PaaS (Platform as a Service) and IaaS (Infrastructure as a Service) like AWS. 3. PaaS (Platform as a Service) There are several smaller players, which provide Platform as a Service and are much easier to use than services like AWS and Azure. With these services you can directly deploy your React or other web-apps, by just hosting them on GitHub and pushing the code. These services are preferred a lot by freelancers, hobbyists and small companies as they don’t require investment in learning complicated services like AWS and Azure. The three most popular PaaS services are Digital Ocean Heroku Netlify 4. Serverless Serverless computing is an execution model where the cloud provider (AWS, Azure, or Google Cloud) is responsible for executing a piece of code by dynamically allocating resources and only charging for the number of resources used to run the code. The code is typically run inside stateless containers that can be triggered by a variety of events including http requests, database events, queuing services, monitoring alerts, file uploads, scheduled events (cron jobs), etc. The code that is sent to the cloud provider for execution is usually in the form of a function. AWS Lambda It is an event-driven, serverless platform which is part of AWS. The various languages supported by AWS Lambda are Node.js, Python, Java, Go, Ruby and .NET. AWS Lambda was designed for use cases such as updates to DynamoDB tables, responding to a website click etc. After that it will “spin down” the database service, to save resources. Azure Functions They are quite similar to AWS Lambda, but are for Microsoft Azure. Azure functions have a browser-based interface to write code to respond to events generated by http requests etc. The service accepts programming languages like C#, F#, Node.js, Python, PHP and Java. Serverless Framework It is an open-source web-framework written using Node.js. The popular services like AWS Lambda, Azure functions and Google cloud functions are based on it. CI/CD A backend developer should know the popular CI/CD (Continuous Integration/Continuous deployment) tools. These tools help to automate the whole process of building, testing and deployment of applications. Github Actions  It is a freely available CI/CD pipeline, which directly integrates to your GitHub based project and can be used in variety of languages. Jenkins Jenkins is the most popular CI/CD automation tool, which helps in building, testing and deployment of applications. Jenkins was written in Java and over the years has been built to support over 1400 plugins, which extend its functionalities. Circle CI Circle CI is also a CI/CD automation tool, which is cloud based and so it is different from Jenkins. It is much easier to use than Jenkins, but has a smaller community and lower user base. SecuritySecurity is an important aspect of any application. Most applications containing user personal data, like email etc, are often targeted by hackers. OWASP The Open Web Application Security Project (or OWASP), is a non-profit organization dedicated to web application security. They have free material available on their website, making it possible for anyone to improve their web application security. Protecting Services & databases against threats Hackers target databases of popular web-apps on a regular basis to get sensitive information about their customers. This data is then sold to the highest bidder on the dark-net. When such public breaches are reported, then it's a reputation loss for the enterprise also. So, a lot of emphasis should be given to Authentication, Access, Backups, and Encryption while setting up a database. The databases should also be monitored for any suspicious activities. Besides this the API routes also need to be protected, so that the hacker cannot manipulate them. Career roles Most of the companies hire Frontend developers, Backend developers and DevOps engineers separately. This is because most of the enterprise projects are huge, in which roles and responsibilities are distributed. But there is a huge demand for Full Stack developers in the startup sector in US and India. These companies need specialists who can get the product out as soon as possible with agile and small teams. Top companies hiringAlmost every company on the planet is hiring web-developers or outsourcing the development work. Since the past decade, the demand for developers has risen exponentially. The top technology companies which hire full stack developers are Facebook, Amazon, Apple, Netflix, Google, Uber, Flipkart, Microsoft and more.  The sites of each of these companies are web-apps (excluding Apple and Microsoft), with complex frontend and backend systems. The frontend generally consists of React or Angular and the backend is a combination of various technologies. The DevOps part is also quite important in these web-apps as they handle millions of concurrent connections at once.Salaries  The salary of a beginner Frontend developer in India starts from Rs. 300,000($ 3980) per year in service-based companies to Rs. 12,00,000($ 15,971) per year in the top tech companies mentioned above. The salary of a Beginner Full-Stack developer in India starts at Rs. 4,50,000 ($ 5989) per year in service companies to Rs. 12,00,000($ 15,971) per year in top tech companies. The salary for an entry level Frontend developer in USA is $ 59,213 per year and for an entry level Full stack developer is $ 61,042 per year.Below are some sources for salaries. Top regions where there is demand There are plenty of remote and freelancing opportunities in web-development across the world. The two countries with most developers and top tech companies are USA and India. Silicon Valley, which is the San Francisco Bay Area, in Northern California, USA is the hub of technology companies.  The top city in India to start a developer job is the Silicon Valley of India – Bengaluru. The number of jobs is more than all the other cities combined and it also has a very good startup ecosystem. Almost all the big technology companies mentioned earlier and top Indian service companies are located in the city. After Bengaluru, the city where the greatest number of technology jobs are based is Hyderabad, followed by Chennai and then Pune. Entry PointsThe demand for web-developers is high and anyone with a passion for creating apps can become a web-developer. An Engineering degree is not mandatory to land a job as a web developer.  The most in-demand skill today and for the next 5 years is React and its ecosystem. So, if you know HTML, CSS, JavaScript and React, it is impossible to not get a job. Career Pathway  Most people start as an intern Front-end developer or Intern Full-Stack developer and in many cases Intern Backend developer. Many companies directly hire junior Frontend/Backend/Full-stack developers.  After that, the next step is the role of Senior Frontend/Backend/Full-stack developers. Many Frontend and Backend developers become full stack developers at this level, by learning additional technologies. Senior resources in Frontend/Backend/Full-stack can then go on to assume Team Lead roles. These people manage small teams in addition to being individual contributors.  After this a professional can become a Project manager, whose main responsibility is managing the team. Another role is that of Technical Project Manager, who manages the team and also has hands-on knowledge in Technology. The last role at this level is that of a Software Architect, who handles and designs big projects and has to look at every aspect of the technology to create the enterprise app. Generally Full-stack developers are preferred in this role, as they need to know all technologies. The highest career milestone is CTO or Chief Technology Officer, who handles all the technology teams and makes all technology decisions in a Technology company. Job SpecializationThere are some Full stack development specializations which I see nowadays in the industry. Full stack developers who work with React in the Frontend and Java in the Backend are in great demand. Similarly, developers who work with Angular in the Frontend and .NET in the backend are in great demand.How KnowledgeHut can helpAll these free resources are a great place to start your Frontend or Full-Stack journey. Beside these there are many other free resources on the internet, but they may not be organized and may not have a structured approach.  This is where KnowledgeHut can make a difference and serve as a one stop shop alternative with its comprehensive Instructor-led live classes. The courses are taught by Industry experts and are perfect for aspirants who wish to become Frontend or FullStack developers.Links for some of the popular courses by KnowledgeHut are appended below-CSS3JavaScriptReactJSNodeJSDevopsConclusion This completes our article on the Full stack developer journey by combining both the Frontend and backend roadmap. There are many people who become backend developers first by working on languages like Java and then go on to learn React to become full stack developers.  Again, many developers learn front-end development first with frameworks like React, and then become full stack developers by learning Node.JS. This path is easier for developers because both React and Node.JS use the same language which is JavaScript.We hope you have found this blog useful, and can now take the right path to become a full stack developer. Good luck on your learning journey!
9561
The 2021 Learning Path To Becoming a Full Stack We...

Full stack developer roles are among the hottest c... Read More