Search

Web Development blog posts

Installation of React on Mac

Hello learners! In this tutorial we are going to learn the installation of React.js library on macOS. React.js is a library which helps developers to develop highly efficient data-driven SPA apps. It is based on functional programming, relies on the concept of immutability and encourages component-based architecture based on Single reusability principle.Before we perform the installation steps, we need to look at the prerequisites needed for installation.1. PrerequisiteSystem requirements: mac OS > 10.10Minimum RAM: 4 GBStorage space: 10 GB available spaceInternet browser: Chrome, Safari, Opera, Microsoft EdgeInternet connectivity: 512 kbps and above2. Introduction to ReactIn this tutorial, we will install the react library on macOS. Before the installation, we need to have a quick understanding of React.React is a library which helps web developers and architects to serve the needs of customers having demands of high data flow and fast responsive UIs in the context of data.It is based on the components-based architecture. The webpage can be represented in the form of Parent and Child based components.  It relies heavily on Virtual DOM, which acts as a performance optimization to DOM operations.A Web page which is composed of HTML has a DOM tree, with the help of which the web page is rendered by the browser.When the user is interacting on a page, it involves addition and insertion of information based on the user activity.  for e.g. A user has added an item to the cart. The cart is showing the updated item to reflect the user’s decision.Behind the scene, the HTML document undergoes a certain transform which helps to share the updated page. As we have mentioned, the HTML document is represented by the DOM tree. In the above scenario, the DOM needs some changes which involve addition and deletion of certain HTML nodes. This helps to show the relevant information which represents what a user is trying to achieve in the context of updating his buying choice.For this insertion and deletion operation on HTML DOM, there is a memory cost involved.Virtual DOM acts as a performance optimizer as far as the DOM update operations are concerned.  It maintains two copies; one is the real copy of the DOM (react DOM) and another one is the change to be done. The process by which minimal change takes place on the react DOM is also studied under the process called reconciliation.To understand the DOM we can visualise it as a tree.  The tree has roots and branches. In a similar manner the DOM has the HTML element at the top and down below there are nodes which are connected to the parent node. In terms of tree analogy, we can represent the parent node as the trunk, with various nodes connected to the trunk. And on these nodes, the insertion and deletion operations get optimized by using React.3. A short intro to Node.js & npmRyan Dahl is the inventor of Node.js.Node.js code is an open source, cross-platform, JavaScript runtime environment that runs JavaScript code. It is based on the Chrome V8 engine. Chrome V8 engine is written in C++. It runs on Windows, macOS and Linux.After installation of Node.js, we can run the react based project locally on our system during development. This also allows us to deploy our app on the production server.Some of the features of Node.js include:a. Uses JavaScript as primary languageb. Non-blocking I/Oc. Supports Asynchronous programmingd. Can handle multiple connections requests by using a single serverNode.js allows us to perform read, write operations on the server.It also provides the functionality to work with the databases.Npmjs.org is an online code repository of thousand modules (npm) and it allows us to install node modules using basic commands. Some modules are independent and some are interrelated to run effectively, due to dependencies between them.Node.js hosts several modules and instead of building functionality from scratch, it is easier for us to look for a module and reuse and extend its functionality. Developer projects generally have time and budget constraints. For the developer community, npmjs.org acts as a lifesaver as far as the Node.js based development is concerned.4. Download Node.js and installationTo install Node.js there are various steps.  It can be installed by visiting https://nodejs.org/en/download/Once we have downloaded the Node.js version based on the operating system, we can perform the installation steps.One thing we need to note is that NPM is auto-installed with Node.js installation.We need to click on the package file which we have downloaded node-v14.15.1.pkgIn the below installation we can see it will install Node.js  v14.15.1 and npm v6.14.8When we click on the Continue button, the installer will ask to ‘Read Licence’.  It also shows two-buttons-- Disagree and Agree.To install the Node.js we need to click on Agree.To proceed further we need to specify the Login password to continue the installation.In the below screenshot the user has administrative rights for software installation. So, the admin needs to type the password in order to proceed further.After clicking on the Install Software button, click on the Install button.In the next screen, the progress bar will indicate the installation progress.Post-installation, it will provide us with a summary as below.After closing this window by clicking on the close button, we need to verify whether we have installed the said version of Node.jsTo open command terminal, press Command + Space barThis will open Spotlight search as below.We need to type Terminal and hit enter.Once the terminal is visible, we need to type the following commandnode - vAs we can see it is showing us the node version (v14.15.1) as in the screenshot.So, we have installed Node version 14. Each build is denoted by semantic versioning. The first digit, in this case, is 14, which represents a major release. The second digit represents new features with the release and the third digit represents patch and bug fixes as associated with the major release.Node.js installation by command line.As an alternative method, we can install node.js by the terminal as well. But as a prerequisite, we need to have homebrew (https://docs.brew.sh/Installation)  in MacOS.We are assuming, we have homebrew installed in our system.And to proceed with the command-line installation, we need to open the terminal and type the following command.brew - vThe above command will inform us about the homebrew version.To update the brew, type the following commandbrew updateAfter the above command has been executed, we need to typebrew install nodeThe installation will take some time, so give some time to the system and be patient.To verify the Node.js installation usenode -vTo verify the npm installation usenpm -vCongratulations, we have installed Node.js and NPM.5. Create-react-app for react app on macOSNow, we are going to install create-react-app on macOS.Create-react-app is a quick way to set up a single page application code with minimal steps and no configuration.Let’s proceed with the installation steps.Please type the following command in the terminal to create a folder with the name react-app. mkdir react-appThen navigate to directory react-app as follows:cd react-appTo verify directory, type command and enter as belowpwdOnce we have confirmed that we are in the right directory type below command.npx create-react-app my-appnpx is a module which is included with npm.The installation steps as shown in the above screenshot will take some time.So, sit back and relax.Once the above command has been executed successfully....….navigate to my-app directorycd  my-appAnd typenpm startWhen the command is executed successfully, it will open the browser at localhost:3000 in the browser.And we can give ourselves a pat on back for the small win!6. Download and Install React (Explicit command)This step is for awareness only.In the previous step, we have not explicitly installed React.js as this is installed with the help of create-react-app package.We can also install the React.js  by using the following command.  And we may need to install the module dependencies on our own.npm install react --save7. File folder and structureWe can see that we have not touched the codebase but found the minimal single page web application running on our macOS.To see the code structure, we need to open the code editor e.g. Sublime, Atom etc.And open the folder my-appAs we can see, there are various folders and at a high level there are below folders:node_modules public srcIn the public folder, we can see index.html. This is the page template.The index.js in src folder is the JavaScript entry point.The app is displaying the code from the App.js in the src folder.In the my-app folder, the package.json is an important file which mentions the app name and module dependencies. Feel free to explore further.8. Summary (conclusion)In this tutorial, we have learnt about React.js, and the component-based architecture model in React.js. We also had a high-level overview of the virtual DOM.We touched on the concept of reconciliation, the usage of Node.js in the world of JavaScript and its capability to handle non-blocking I/O output to fulfil client connection requests simultaneously.We have checked two methods for Node.js installation, namely with the package manager and another one by using the command line.To install React.js, we have relied on the create-react-app module for a quick start. We can also install the React.js by command line. To prevent being overwhelmed with too many details we have picked the create-react-app method for this tutorial. We created our first react app and saw it running.To become familiar with the code in terms of development perspective, we quickly checked the important files which are running the app.
Installation of React on Mac
Gaurav

Installation of React on Mac

Hello learners! In this tutorial we are going to learn the installation of React.js library on macOS. React.js is a library which helps developers to develop highly efficient data-driven SPA apps. It is based on functional programming, relies on the concept of immutability and encourages component-based architecture based on Single reusability principle.Before we perform the installation steps, we need to look at the prerequisites needed for installation.1. PrerequisiteSystem requirements: mac OS > 10.10Minimum RAM: 4 GBStorage space: 10 GB available spaceInternet browser: Chrome, Safari, Opera, Microsoft EdgeInternet connectivity: 512 kbps and above2. Introduction to ReactIn this tutorial, we will install the react library on macOS. Before the installation, we need to have a quick understanding of React.React is a library which helps web developers and architects to serve the needs of customers having demands of high data flow and fast responsive UIs in the context of data.It is based on the components-based architecture. The webpage can be represented in the form of Parent and Child based components.  It relies heavily on Virtual DOM, which acts as a performance optimization to DOM operations.A Web page which is composed of HTML has a DOM tree, with the help of which the web page is rendered by the browser.When the user is interacting on a page, it involves addition and insertion of information based on the user activity.  for e.g. A user has added an item to the cart. The cart is showing the updated item to reflect the user’s decision.Behind the scene, the HTML document undergoes a certain transform which helps to share the updated page. As we have mentioned, the HTML document is represented by the DOM tree. In the above scenario, the DOM needs some changes which involve addition and deletion of certain HTML nodes. This helps to show the relevant information which represents what a user is trying to achieve in the context of updating his buying choice.For this insertion and deletion operation on HTML DOM, there is a memory cost involved.Virtual DOM acts as a performance optimizer as far as the DOM update operations are concerned.  It maintains two copies; one is the real copy of the DOM (react DOM) and another one is the change to be done. The process by which minimal change takes place on the react DOM is also studied under the process called reconciliation.To understand the DOM we can visualise it as a tree.  The tree has roots and branches. In a similar manner the DOM has the HTML element at the top and down below there are nodes which are connected to the parent node. In terms of tree analogy, we can represent the parent node as the trunk, with various nodes connected to the trunk. And on these nodes, the insertion and deletion operations get optimized by using React.3. A short intro to Node.js & npmRyan Dahl is the inventor of Node.js.Node.js code is an open source, cross-platform, JavaScript runtime environment that runs JavaScript code. It is based on the Chrome V8 engine. Chrome V8 engine is written in C++. It runs on Windows, macOS and Linux.After installation of Node.js, we can run the react based project locally on our system during development. This also allows us to deploy our app on the production server.Some of the features of Node.js include:a. Uses JavaScript as primary languageb. Non-blocking I/Oc. Supports Asynchronous programmingd. Can handle multiple connections requests by using a single serverNode.js allows us to perform read, write operations on the server.It also provides the functionality to work with the databases.Npmjs.org is an online code repository of thousand modules (npm) and it allows us to install node modules using basic commands. Some modules are independent and some are interrelated to run effectively, due to dependencies between them.Node.js hosts several modules and instead of building functionality from scratch, it is easier for us to look for a module and reuse and extend its functionality. Developer projects generally have time and budget constraints. For the developer community, npmjs.org acts as a lifesaver as far as the Node.js based development is concerned.4. Download Node.js and installationTo install Node.js there are various steps.  It can be installed by visiting https://nodejs.org/en/download/Once we have downloaded the Node.js version based on the operating system, we can perform the installation steps.One thing we need to note is that NPM is auto-installed with Node.js installation.We need to click on the package file which we have downloaded node-v14.15.1.pkgIn the below installation we can see it will install Node.js  v14.15.1 and npm v6.14.8When we click on the Continue button, the installer will ask to ‘Read Licence’.  It also shows two-buttons-- Disagree and Agree.To install the Node.js we need to click on Agree.To proceed further we need to specify the Login password to continue the installation.In the below screenshot the user has administrative rights for software installation. So, the admin needs to type the password in order to proceed further.After clicking on the Install Software button, click on the Install button.In the next screen, the progress bar will indicate the installation progress.Post-installation, it will provide us with a summary as below.After closing this window by clicking on the close button, we need to verify whether we have installed the said version of Node.jsTo open command terminal, press Command + Space barThis will open Spotlight search as below.We need to type Terminal and hit enter.Once the terminal is visible, we need to type the following commandnode - vAs we can see it is showing us the node version (v14.15.1) as in the screenshot.So, we have installed Node version 14. Each build is denoted by semantic versioning. The first digit, in this case, is 14, which represents a major release. The second digit represents new features with the release and the third digit represents patch and bug fixes as associated with the major release.Node.js installation by command line.As an alternative method, we can install node.js by the terminal as well. But as a prerequisite, we need to have homebrew (https://docs.brew.sh/Installation)  in MacOS.We are assuming, we have homebrew installed in our system.And to proceed with the command-line installation, we need to open the terminal and type the following command.brew - vThe above command will inform us about the homebrew version.To update the brew, type the following commandbrew updateAfter the above command has been executed, we need to typebrew install nodeThe installation will take some time, so give some time to the system and be patient.To verify the Node.js installation usenode -vTo verify the npm installation usenpm -vCongratulations, we have installed Node.js and NPM.5. Create-react-app for react app on macOSNow, we are going to install create-react-app on macOS.Create-react-app is a quick way to set up a single page application code with minimal steps and no configuration.Let’s proceed with the installation steps.Please type the following command in the terminal to create a folder with the name react-app. mkdir react-appThen navigate to directory react-app as follows:cd react-appTo verify directory, type command and enter as belowpwdOnce we have confirmed that we are in the right directory type below command.npx create-react-app my-appnpx is a module which is included with npm.The installation steps as shown in the above screenshot will take some time.So, sit back and relax.Once the above command has been executed successfully....….navigate to my-app directorycd  my-appAnd typenpm startWhen the command is executed successfully, it will open the browser at localhost:3000 in the browser.And we can give ourselves a pat on back for the small win!6. Download and Install React (Explicit command)This step is for awareness only.In the previous step, we have not explicitly installed React.js as this is installed with the help of create-react-app package.We can also install the React.js  by using the following command.  And we may need to install the module dependencies on our own.npm install react --save7. File folder and structureWe can see that we have not touched the codebase but found the minimal single page web application running on our macOS.To see the code structure, we need to open the code editor e.g. Sublime, Atom etc.And open the folder my-appAs we can see, there are various folders and at a high level there are below folders:node_modules public srcIn the public folder, we can see index.html. This is the page template.The index.js in src folder is the JavaScript entry point.The app is displaying the code from the App.js in the src folder.In the my-app folder, the package.json is an important file which mentions the app name and module dependencies. Feel free to explore further.8. Summary (conclusion)In this tutorial, we have learnt about React.js, and the component-based architecture model in React.js. We also had a high-level overview of the virtual DOM.We touched on the concept of reconciliation, the usage of Node.js in the world of JavaScript and its capability to handle non-blocking I/O output to fulfil client connection requests simultaneously.We have checked two methods for Node.js installation, namely with the package manager and another one by using the command line.To install React.js, we have relied on the create-react-app module for a quick start. We can also install the React.js by command line. To prevent being overwhelmed with too many details we have picked the create-react-app method for this tutorial. We created our first react app and saw it running.To become familiar with the code in terms of development perspective, we quickly checked the important files which are running the app.
3492
Installation of React on Mac

Hello learners! In this tutorial we are going to l... Read More

What is the Use of Axios in React?

While dealing with web applications in React, the most common task is to communicate with backend servers. This is usually done via HTTP protocol.  We are all quite familiar with the very common XML Http Request interface and Fetch API, which allows us to fetch data and make HTTP requests. There is another way to communicate with the backend in React, and in this article we will learn about the awesome library known as Axios and some of the key features of Axios  that have contributed to its popularity among frontend developers. So let’s get started.What is Axios? (A little bit of history) Axios is used to communicate with the backend and it also supports the Promise API that is native to JS ES6.  It is a library which is used to make requests to an API, return data from the API, and then do things with that data in our React application. Axios is a very popular (over 78k stars on Github) HTTP client, which allows us to make HTTP  requests from the browser. Why Do We Need Axios in React? Axios allows us to communicate with APIs easily in our React apps. Though this can also be achieved by other methods like fetch or AJAX, Axios can provide a little more functionality that goes a long way with applications that use React.  Axios is a promise-based library used with Node.js and your browser to make asynchronous JavaScript HTTP requests. When we know we need to implement some promise-based asynchronous HTTP requests in our application, with JavaScript, we usually think of only jQuery’s AJAX or fetch method to get the job done. And while doing so, we are actually going against React!! Did you notice that? So, while React doesn’t care about DOM manipulation at all, why do we need jQuery for our React app? Since React is handling each and everything within its own virtual DOM, perhaps we don’t need  jQuery at all. And hence, Axios becomes a lighter-weight/optimized solution to play around with our HTTP requests. Apart from the above mentioned points, why I personally like AXIOS is because it has a very clean and precise syntax. See  the example code below: Don't worry if you are not familiar with the code, we will learn that later. Using FETCH API:   const getPostsData = () => {   fetch(‘https://jsonplaceholder.typicode.com/posts’)   .then(response => response.json())   .then(data => console.log(data))   .catch(error => console.log(error));   } }  getPostsData();Using AXIOS: const getPostsData = () => {   axios   .get("https://jsonplaceholder.typicode.com/posts")   .then(data => console.log(data.data))   .catch(error => console.log(error));   };  getPostsData();You might be thinking that there isn’t a very big difference but if we consider a POST or Delete or PUT request you can start observing the benefits of using Axios.  Prerequisites In order to use Axios with React, you’ll need the following: Install Node (v 10.7 or above). And if it is already installed, check the version by using npm -v  A React project setup with Create React App or any React boilerplate If you want to learn more about Axios library, head up to this link https://github.com/axios/axios.  Okay, now that we have spent a good amount of time in understanding Axios, let’s turn our attention on how to use Axios with React. Installing Axios In order to use Axios with React, we need to install Axios. It does not come as a native JavaScript API, so that's why we have to manually import into our project. There are many ways to install Axios. You can pick any of them based on your system environment. Open up a new terminal window, move to your project’s root directory, and run any of the following commands to add Axios to your project. Using npm: $ npm install axios  Using bower package manager: $ bower install axios  Using yarn:  $ yarn add axios  Using unpkg CDN:     Using jsDelivr CDN:      It’s not as complicated as you  might think it’d be.  Fetching and Consuming Data with a Axios (GET-POST-DELETE) Web Applications use HTTP requests, for example, GET, POST and PUT, to communicate with APIs. Axios makes our life simple as it is easy for us now to perform these commands. In this section, we will learn how to use the Axios to make REST API calls like GET, POST  and DELETE in React App. So let’s get started. Performing GET Request with Axios Let’s create a new component named My List and hook it into the component DidMount lifecycle as shown below. After that we will fetch data with Get request by importing axios. Here we are using JSON placeholder API for fetching the dummy list data of users. import React from 'react';  import axios from 'axios';  export default class MyList extends React.Component {   state = {   persons: []   }  componentDidMount() {   axios.get(`https://jsonplaceholder.typicode.com/users`)   .then(response => { const users = response.data;   this.setState ({users});   })   }  render() {   return (   < ul >   {this.state.users.map (user => {user.name} )}   < /ul >   )   }  }In the above component named MyList, we have imported Axios first. axios.get(--URL--) is used to get a promise which will return a response object. The received data in response.data is assigned to the user's object.  We can also retrieve other Information like status code and others received with the response. Performing POST Request with Axios Now let’s create another component named AddUser for using the POST request which will add a user in the user list. (a.ka. Adding data into database) import React from 'react'; import axios from 'axios'; export default class AddUser extends React.Component {  state = {  userName: '',  }  handleChange = event => {  this.setState({ userName: event.target.value });  }  handleSubmit = event => {  event.preventDefault();  const user = {  userName: this.state.userName  };  axios.post(`https://jsonplaceholder.typicode.com/users`, { user })  .then(res => {  console.log(res);  console.log(res.data);  })[Text Wrapping Break] }  render() {  return (        User Name:      Add      )  }  }In the above example, we have made a HTTP Post request to modify the database, which is a user list and added a new user to the database. Because we've initialized the state, in handleChange() we have updated the state when the API request returns data successfully. Performing POST Request with Axios Finally, the delete method. axios.delete is used to make a Delete request to the server. axiox.delete accepts two parameters: url and optional config.  axios.delete(url, { data: { foo: "bar" }, headers: { "Authorization": "***" } }); We can use config.data to set the request body and headers as shown in the below snippet. Consider the same component as above and modify the request as follows: handleSubmit = event => {   event.preventDefault();   axios.delete(`https://jsonplaceholder.typicode.com/users/${this.state.userName}`)   .then(res => {   console.log(res);   console.log(res.data);   })  } And you are done! — you’ve got a transformed and simplified React appSending custom headers with Axios Sending custom headers with Axios is very simple and straightforward.  It is done by passing an object containing the headers as the last argument.  See the below code reference:  const options = {   headers: {'X-Custom-Header': 'value'}  };  axios.post('/save', { a: 50 }, options);Looking at the response object When we send a request to server and it is successful, our then() callback will receive a response object which can have the following properties: data: It is the payload returned from the server. By default, Axios expects JSON and will parse this back into a JavaScript object for you. status: It is basically the HTTP code returned from the server. statusText: it refers to the HTTP status message returned by the server. headers: It contains all the headers sent back by the server. config: It has the original request configuration. request: It is the actual XMLHttpRequest object (when it is running in a browser)Looking at the error object And if there’s a problem with the request, the promise will be rejected with an error object containing at least one or few of the following properties: message: the error message text. response: the response object (if received) as described in the previous section. request: the actual XMLHttpRequest object (when running in a browser). config: the original request configuration. Features of Axios Library as per the Documentation: Automatically transforms for JSON data Axios is intelligent because it automatically converts a response to JSON, so while using Axios we usually skip the step of converting the response to JSON, unlike we do in Fetch() Transform request and response data Make HTTP requests from Node.js Make XMLHttpRequests from the browser Client-side support for protecting against XSRF Supports the Promise API Intercept request and response: HTTP interceptors are used when we need to change HTTP requests from our application to the server. Axios provides a way to intercept HTTP requests.  And hence Interceptors provide us the ability to do that without writing any extra code. Has an ability to cancel requests It has a built-in feature that provides client-side protection against cross-site request forgery. In case you want to dig in and learn more about these features, head up to the official documentation of AXIOS. MAKING MULTIPLE REQUESTS WITH AXIOS With Axios we get an ability to make multiple HTTP requests and handle them simultaneously using the axios.all() method. This method takes in an array of arguments and in return we get a single promise object that only resolves when all the arguments passed in the array have been resolved. Look at the below example, where we are making multiple requests to the GitHub api using the axios.all() method. axios.all([   axios.get('https://api.github.com/users/defunkt),   axios.get('https://api.github.com/users/evanphx)  ])  .then(response => {   console.log('Date created: ', response[0].data.created_at);   console.log('Date created: ', response[1].data.created_at);  }); What will happen in the above code is that it will make simultaneous requests to an array of arguments in parallel, return the response data and will console the created_at object from each of the API responses.  Think About Abstraction  In Axios it’s quite possible to create a base instance where we can drop the URL for our API as shown below:   const api = axios.create({ baseURL: "https://api.github.com/users/evanphx" });And then simply abstract the URL like shown:  async getPostsData() { const response = await api.get();   try {   this.setState({   posts: response.data.posts,   isLoading: false   });   } catch (error) {   this.setState({ error, isLoading: false });   }  }Shorthand Methods in Axios  You have already seen that Axios provides an easy-to-use API contract model in a compact package for most of our HTTP communication needs. Do you know that Axios has some shorthand methods for performing different HTTP requests?  Check them below:  axios.request(config) axios.get(url[, config]) axios.delete(url[, config]) axios.head(url[, config]) axios.options(url[, config]) axios.post(url[, data[, config]]) axios.put(url[, data[, config]]) axios.patch(url[, data[, config]]) Some Awesome Facts about Axios  Wondering about some cool facts about Axios? Let’s check them out! For Axios, there is no need for a browser environment. This neat simple library also works on the server-side!  And hence we can use Axios in our Node applications as well. Apart from fetching or retrieving data, with the help of Axios we can also check the token expiry while requesting data for client-side and server-side. And when the token is already expired we can call an API to get the new token and continue the previous API request.  In Axios, monitoring the upload and download progress is quite simple. How? Just set a callback in the request config as shown below, and enjoy. axios({   method: "get",   url: "/myFilePath",   responseType: "blob",   onDownloadProgress: (progressEvent) => { const percentCompleted = Math.round(   (progressEvent.loaded * 100) / progressEvent.total   );  console.log(percentCompleted)   this.setState({   loadingPercent: percentCompleted,   });   },  }).then((response) => {   alert("We are Ready!");  });Conclusion I hope this article has helped you in understanding about Axios and its usage for various features like fetching or retrieving data and handling responses.  In this article, we saw several practical examples to check the power of Axios inside a React application to create HTTP requests and handle responses. We also got an idea about why it is a better approach than a normal fetch api.  So what are you waiting for? Go ahead and give Axios a try. It will definitely make your life easier. Happy Learning.
5649
What is the Use of Axios in React?

While dealing with web applications in React, the... Read More

Install And Setup React App on Ubuntu

React is a JavaScript library for building user interfaces. It is opensource and maintained by Facebook.You can read more about React here:  https://reactjs.org/docs/getting-started.htmlIn this blog we are going to learn how to install and setup a React App on Ubuntu (version 16 and above).PrerequisitesThis blog assumes that you are using Ubuntu 16 or above versions and you have all the privileges to install the software in the machine, and also have access to the required websites mentioned in the blog.System Requirements:Ubuntu 16 or aboveMinimum 4GB RAMVisual Studio Code installed.Why should we choose React, and what are its advantages?React is built on JavaScript which makes it easier to learn and easier to use.React is component based which means we can write re-usable components. Start with small things, which you use to build bigger things, which you use to build apps.React is lightweight compared to Angular; which in turn makes your application faster to load—which is very important from the user’s point of view.React ensures faster rendering of DOM (document object model), this has been achieved by the introduction of Virtual DOM-currently, one of the benefits of using React for heavy loaded and dynamic software solutions.React has a helpful and interactive developer toolset which makes it easy to debug. React Developer Tools is a browser extension available for both Chrome and Firefox. It enables developers to observe reactive component hierarchies, discover child and parent components, and inspect their current state and props.  React uses JSX(JavaScript XML) which has HTML-like syntax, making it easy to code and understand.React has strong community support on Github, Stackoverflow and many other platforms.React is SEO friendly.There are certainly many other nice features about using React.What is Node.js?Node.js is a JavaScript runtime built on Chrome's V8 JavaScript engine. Node.js is an Open Source Server Environment that is free and runs on almost all Operating Systems (Windows, Linux, Unix, Mac OS X, etc.).You can read more about Nodejs here: https://nodejs.org/en/Why do we need Nodejs for React apps?Node.js lets developers use JavaScript to develop variety of applications like network applications, command line tools, web APIs, mobile applications, web applications etc.React usually runs on Node Server in development, but we can make use of other Servers likes Apache or Nginix to run React App in production. You do not need NodeJS to run React in production.What is NPM, why do we need NPM for React apps?NPM (Node Package Manager) is a dependency management tool for JavaScript applications. It is Open Source and also has command line utility for interacting with the application that aids in package installation, version management, and dependency management.React does not ship with all the features by itself, so it uses external packages to add the required features to the React application. These packages are maintained by NPM (Node package manager) which is shipped with Nodejs in development.You can read more about npm here: https://nodejs.org/en/knowledge/getting-started/npm/what-is-npm/We can use yarn instead of NPM during development and production for React apps.Install Node.jsThere are many ways to install Node.js in an Ubuntu machine.Install Node.js from the Ubuntu repositoryInstall Using a PPA (personal package archive)Using the first method we will not get the latest version of Node.js installed so we will choose the second method where we will get the latest version of Node.js installed.Installing Using a PPA (personal package archive)To get the latest version of Node.js installed on ubuntu, add a PPA (personal package archive). It is maintained by NodeSource.Open terminal and run below commands:Install curl: Run below command on terminalCommand: sudo apt-get install curlSet the NodeSource PPA: Run below command on terminalCommand: curl -sL https://deb.nodesource.com/setup_current.x | sudo -E bash –The PPA will be added to your configuration and your local package cache will be updated automatically.You can read more about available versions of Node.js in nodesource here: https://github.com/nodesource/distributions#debInstall Node.js: Run the below command on terminalCommand: sudo apt-get install -y nodejsCheck for Node.js Installation: Run below command on terminalCommand: node -vIt has to show the version of node installed in this case v15.4.0Now let's see how we can install and setup React app in Ubuntu machineUsing create-react-app (installing create-react-app using npm)Using npx (Recommended in React docs)Using create-react-app (npm)In setting up a React project we come across tools like babel and webpack which are not easy to understand and configure for a person who is new to React and JavaScript. There are several tools that help to sort this problem. One of them is create-react-app. This is the easiest to setup. Create-react-app comes with production grade configurations pre-built. You can alter the configurations by ejecting from the create-react-app as well.Follow the below steps to install using npm create-react-appGo into your desired location where you want to start your react app using ‘cd’ command Run below command to install create-react-app using npm Command: npm install -g create-react-appNow Run create-react-app on terminal to setup a React-app. Command: create-react-app hello-worldThis creates a folder with the name hello-world. You can navigate into the folder using ‘cd’ command and look at the project structure.This gives the React app which we can use, but React recommends using npx.Using npx command:npx is the package runner, since npm version 5.2.0 npx is pre-bundled with npm.Read more about differences npx and npm here: https://www.freecodecamp.org/news/npm-vs-npx-whats-the-difference/Follow the below steps to setup using npx.Go into your desired location where you want to start your react app using ‘cd’ commandRun the below command to setup React app using npxCommand: npx create-react-app my-appThat’s it! Your React app is ready with a single command.This creates a folder with the name hello-world. You can navigate into the folder using ‘cd’ command.  Now open the project in vs-codeWhen you open the project in visual studio code the structure looks like this.Now let's have a look at the files and folders we have:node_modules: This folder is managed by package manager (npm) and contains all the project library dependencies. We should not edit any file inside this folder.public: This folder contains the assets that should be served publicly without any restrictions and contains files like index.html, favicon, manifest.jsonsrc:  This is the folder that contains all the files that are used to create web applications. As a react developer you are likely to spend a lot of time in this folder creating components and other sources of code..gitignore: This file has all the assets which should be ignored by git while we publish our code to GitHub eg: node_modulespackage.json: This is a JSON file which has all information about the app such as name, dependencies, scripts we use to run the application etc.Readme.md: This is a markdown file where you specify the things which you want to show when someone visits your project on GitHub.Now let's run our first React app!Open the terminal integrated with Visual studio code or just stay in the ubuntu terminal; either is fine. Let's use the integrated terminal.Run the app using the following command: Command: npm startThis opens the app in your favourite browser as shown below:Now, let's make our first code changes:On navigating to src folder, you will find App.js file, through which the whole app is run inside the browser. Change the code as you see below and save by hitting ctrl+s.Now look at the browser where the app is running. It looks like the one in the image below.Congratulations on making your first React app!What you have learnt:What is React and why it should be usedWhat is Node.js, and how it should be installed on Ubuntu.What is npmWhat is create-react-appHow to setup React-app on UbuntuHow to run the React-app  How to make code changes to create your first React application.React has rapid changes for every new version. It is important to keep yourself updated with the latest releases of React, so that you can make your life as a React developer easier!
2315
Install And Setup React App on Ubuntu

React is a JavaScript library for building user in... Read More

Instal React Js on Windows

IntroductionIn this tutorial, we will learn how to install React.js on Windows.React.js is a library which helps us to build and create front end interfaces for Single page applications and it utilises the power of virtual DOM.React.js was an inhouse project of Facebook, and it was made open to the public in the year 2013. The adoption of React.js has seen an upward curve since its avantages have been realized. Various startups and established organizations are now adopting the technology and upgrading their technology stack.1. Prerequisite for WindowsTo install React on Windows, your system will require the minimum configuration as below:Windows XP, Windows 7 (32/64 bit) or higherMinimum 4 GB RAM and higher10 GB available space on the hard diskAt least one Internet Browser e.g. Chrome, Firefox, Microsoft Edge etc.Node.jsActive internet connection minimum speed 512kbps and above.At least one installed code Editor to test and debug your code e.g.  Atom https://atom.io/Sublime https://www.sublimetext.com/Visual studio code https://code.visualstudio.com/download.2. Introduction to React.jsReact.js is a library written in TypeScript. It utilises the syntax of the modern version of JavaScript as described by ES6 and its higher version.Applications built using React.js use the Single reusability principle. This advocates the idea of building web pages and applications using components and unidirectional flow. In React.js we have the concept of states and the concept of immutability. Components have hierarchy in terms of Parent and Child components. A component in case of React.js can be thought of as a piece of code which is based on the principle of pure functions. We will look into the pure component later. First, let’s understand what a state is. For e.g. To become a member of a service, the user fills his information on the registration page. While filling the details there can be many states of the form, for e.g. When the form field is empty or when the form field has witnessed some error on some particular field, which needs to be corrected; or when after correction, the form data has been validated and is ready for submission. So, at a broad level, the registration form has been through various states. These states represent at which level the application is, in terms of interacting with the end-user. Each level of interaction for this form is represented by the state, from an empty form to being a fully filled form with a display of an error for certain fields and the validated form. In React.js, we have the component based on the pure function. A pure function can be memorised as a piece of code, which does one task and does it pretty well. For a certain input, it always returns the same output, so this means we are increasing predictability of the code. Since React.js follows a certain code pattern and principles in order to work, it lowers the curve of the knowledge gap; whether you are one-person or a team of developers working mutually.3. Introduction to Node.js and NPM on WindowsTo run React.js we will require Node.js on our system.Node.js is a server which will help us to run the React.js code.It is based on non-blocking input and output and the Chrome V8 JavaScript engine. The Node.js code is open source.NPM which is an abbreviation of Node package manager, npmjs.com is supported by various developers around the world. It has various node modules, using which developers can host and publish their modules on the open-source community.  It hosts modules in private and public visibility.A module carries code which exists to serve high or low level functionalities. In terms of code adoption and availability of various modules it gives an edge and tries to make the developer more productive.  We can plug in and plug out the module. Some modules are dependent on other modules; which is defined as dependency among modules.While building an application, a developer can pick the module, tweak and remix it to suit the application needs, and can then release to the open-source community. So, instead of reinventing the wheel, it is like picking a wheel (npm module) from npmjs.com, giving it further momentum and giving it back to the open source community.4. Download and Install Node.jsTo install Node.js we need to go to the URL https://nodejs.orgDepending upon our Windows OS version in terms of 32 Bit or 64 Bit, we can pick the installer and install that version.  In this tutorial I am using Windows 8, 64 Bit.  The Node.js installer includes NPM. It is best to install the even numbered version of NPM.Depending upon your operating system, the Nodejs.org home page will show the Download button and recommended LTS version.After the download is complete we will go to the downloads folder and run the installer.The installer will show the below Setup Wizard. Click next.The next screen will ask for the End-user License Agreement. Select the checkbox at the bottom right to provide your consent and click on Next to proceed with the installation.The installer will ask for Destination folder and the default path set by installation is C:\Program Files\nodejs\Click on Next buttonThe above screen is an important step in the installation process. And if you see closely it also sets the environmental path variables to command prompt on Windows.Click on Next to continue with the installation.The Windows OS may ask you to allow Node.js installation and make changes.Click on Yes button.During the installation, if you have allowed for Chocolatey and required modules installation for C++ and Python, you will see the UI below in the command prompt. This installation requires 3 Gb of free disk space. In this tutorial this step is not required, so we are skipping this step by closing the window.If you are interested in installing it, press Enter to continue.Once the istallation is complete you need to verify the Node.js installation.  For this we will use the command prompt.To run command promptPress keys Win+RAnd type cmd in the window below.Next Click on Ok or Press Enter on the keyboard.5. Installation of ReactAfter installation of Node.js we need to install React.To check the Node.js version, open the Windows command prompt. Press Win+R and type cmd. In the command line, type   node -v to see its version. We can also check for npm version, which is installed with Node.js, with the following command npm -v After running these commands, we can check the node version v14.15.1 and npm version 6.14.8As we have confirmed the Node.js installation we can proceed to the next steps.While in the command prompt, we have navigated to a folder called Codefactory by following the command cd CodefactoryIn this folder we have created a folder  called react-windows by using the command mkdir react-windows.After the folder react-windows has been created, we will change the directory to react-windows with the command cd react-windows React.js can be installed in various ways. Now, we will type npm init. It will ask for the below configuration line by line. Insert your input, followed by Enter keypress to proceed with the next configuration.   At the end of the configuration it will confirm for the inputs you have entered. If you are happy with the configuration data, type yes and enter to continue.The npm init will help us to create a package.json file.Now, the next step to install React.js requires us to go to the command prompt and type the following command in the react-windows directory.npm install --save reactAnd after the above command npm install --save react-domBehind the scene, these commands fetch the specified module from npmjs.com and download it in the local codebase.Let's have a look at the react-windows folder. Here we can see some newly created directories in node_modules.So, in this tutorial, we have learned to install React and reactDOM. But to see the React.js SPA (single page app) there is more work to be done in the above code.As an alternative and fast approach we can do it via create-react-appLet us move to Codefactory folder and with the command cd.. create another folder react-cliNext, type the following command mkdir react-cliNow we will use create-react-app module and type the following commandPlease note that my-fast-app is the name of your app. This is an example and you can be creative in choosing your own name.npx create-react-app my-fast-appIf we see closely it will take care of the rest of the installation steps, and react, react-dom and other related modules are installed automatically.This process is a little data intensive, so please be patient while the download and installation happensWhen the above step gets completed the command prompt displays the below output.Now, let us run our first react app, by navigating to my-fast-app directory as belowcd my-fast-appAnd enter the next command as npm startThe npm command will show the application in the browser. http://localhost:3000And if you are running node.js for the first time using npm command, it will ask for permission to allow access and we need to allow access to run.As we are using a code editor we can have a look at the directory structure and some of the important files, such as index.html in the public folder, in src folder the index.js and App.js. The src folder contains the react component which we can build further on this codebase. index.js is the js invocation point for react app.This index.js is linked with the App.js, which is responsible for showing the content in the browser. That’s what we see on the demo page.Let’s edit the App.js by going to line 10 and adding the following codeTalk is cheap, show me the CodeOnce you save the file by Ctrl+SThe code will be auto refreshed in the browser, after compiling.It will show us the following output.So, now feel free to change messages and alter the page layout and structure for  experimentation.If you are familiar with CSS, you may also change the page style using App.css and tinker with the code as well.SummaryIn this tutorial, we have introduced you to React.js . Its impact in terms of building modern front end interfaces using component-based architecture is significant. We have also touched upon the concept of states, immutability and pure functions.We have got a brief introduction to the Node.js server and NPM modules, the capabilities of Node.js server and the power of the open source community in the npmjs.com.To install React, Node.js installation is a prerequisite.There are various methods for installation. Once we have installed Node.js, React can be installed either by npm commands or by using the create-react-app module.
4504
Instal React Js on Windows

IntroductionIn this tutorial, we will learn how to... Read More

Understanding the React useReducer Hook

IntroductionThe introduction of Hooks in React brought up a new way of writing and thinking about React applications. One of the most popular Hooks among developers so far is useReducer, which allows us to handle some complex state manipulations and updates, and this is what we’ll be learning about in this article.In React there are two main hooks that are used for state management, and we all know them. These are:useState, anduseReducerYou might have heard or used React.useState hook, and if not you can directly read React’s official documentation about Hooks here.Have you ever found any difficulty in choosing a state management library to manage and handle a global state in a React app? Or, what if you need to manage more complicated data structures or perform any side effects?Thinking over these concepts is quite tricky and time-consuming.Well, this is pretty much what we are going to learn and cover in this article, so read on!  PrerequisitesIn order to get the full benefits of this article, I’d recommend you to double check this prerequisite list and set up the environment as suggested.Npm or Yarn installedNode.js version >= 12.x.x installedcreate-react-app cli installed or use npxBasics of React Hooks, (if not kindly read this first)What is a Reducer, anyway?What is the first thing that comes up in your mind when you hear the term reducer in React?For me, I am always reminded of JavaScript's Array.reducer() function.The only job of a reducer is to Reduce!We all know that the original reduce() method in JavaScript executes a given function for each value of an array  considering from left-to-right. And, here React.useReducer in fact, is like a mini Redux reducer.  A reducer is basically a function which determines a change to an application’s state. It takes the help of an action by using it to receive and determine that particular change.In react we have a lot of options, like Redux, that can help to manage the application’s state changes in a single store. Here we will learn about how we can make use of a reducer to manage shared state in an application.Reducer is one of the new custom Hooks introduced in React since v16.8. It allows you to update parts of your component’s state when certain actions are dispatched, and it is very similar to how Redux works.The reducer in ‘useReducer’ comes from Redux, which in turn borrowed it from JavaScript’s Array.reduce().It carries an initial state and a reducer function as its arguments and then provides a state variable and a dispatch function to enable us to update the state. If you’re familiar with how Redux updates the store through reducers and actions, then you already know how useReducer works. And if not, then also we will learn about useReducer functionality in core.So basically, what is useReducer Hook?The useReducer hook is used for complex state manipulations and state transitions.  Just like the other React hooks, we can import useReducer from react as shown in the below snippet:import React, { useReducer } from 'react';React.useReducer is a React hook function that accepts a reducer function, and an initial state.  const [state, dispatch] = useReducer(reducer, initialState);This hook function returns an array with 2 values. The first one is the state value, and the second value is the dispatch function which is further used to trigger an action with the help of array destructuring.  In the context of React, here’s what a typical useReducer pattern looks like:JSX:const reducer = function (currentState, action) { // Make a new state based on the current state and action return newState}const [state, dispatch] = useReducer(reducer, initialValue)// example usage: dispatch({type: "SOMETHING_HAPPENED"}) // Or with an optional "data": dispatch({type: "SOMETHING_HAPPENED", data: newData})Note: The “state” can be of  any kind. It doesn’t have to be an object always. It could be a number, or an array, or anything else.Pretty cool? Now let’s move further and understand how to use useReducer.How to use the useReducer Hook?Earlier we saw the basic useReducer which takes up two arguments: initial state and a reducer function. But useReducer hook actually takes up one more argument including reducer and initial state which is >>> a function to load the initial state lazily.This is usually helpful when we want the initial state to be different depending on some situation and instead of using our actual state, we could create the initial state anywhere, perhaps dynamically, and it will override the initial state.Syntax for the third argument is:const [state, dispatch] = useReducer(reducer, initialArgs, init); Let’s now understand step by step how to use useReducer and understand what’s happening behind the deck.Consider the following classic example of code to see the practical usage of useReducer:// Let’s begin to define the initial state of the component's state const initialState = { count: 0 } // Here is a function will determine how the state is updated function reducer(state, action) {  switch(action.type) { case 'INCREMENT': return { count: state.count + 1 } case 'DECREMENT': return { count: state.count - 1 } case 'REPLACE': return { count: action.newCount } case 'RESET': return { count: 0 } default: return state } } // Now inside our component, we can initialize the state like below const [state, dispatch] = useReducer(reducer, initialState);Explanation:In the above code snippet , we have  first defined an initial state for our componentadded a reducer function that updates that state depending on the action dispatched and,we have finally initialized the state for our component.Now as promised earlier, you don’t require an understanding of Redux to understand this concept. So let’s break down everything and see what’s happening.The initialState variableThis is the default value of our component’s state when it gets mounted for the first time inside the application.The reducer functionThe next step is to update the component’s state when some actions occur. This function tells what the state should contain depending on the action. It returns an object, which is then used to replace / change the state.It takes in two arguments which are a state and an action; wherein state is nothing but your application’s current state, and the action is an object which contains the details of all the actions currently happening.An action may typically look like this:const replaceAction = { type: 'REPLACE', newCount: 10, }It usually contains a type: which denotes what type of action it is. An action can also contain more than one data, which can also be the new value to be updated in the state.Dispatching an actionNow after understanding about the reducer and how it determines the next state for our component through actions, let’s see how actions are dispatched.Dispatch is just like a function which we can pass around to other components through props.You must have noticed that useReducer returns two values in an array. The first one is the state object, and the second one is a function called dispatch. This is what is used to dispatch an action.For example, if we want to dispatch replaceAction defined in the above example, we’d do something like this:dispatch(replaceAction) // or dispatch({ type: 'REPLACE', newCount: 10, })Summarising a bit here, hence for using useReducer we need the following:Defining an initial stateProviding a function which contains actions that can update the state.Trigger useReducer to dispatch the updated stateUnderstanding useReducer with examplesLet’s play with some real examples now to understand the concept better:Example:1 Simple Classic Counter ExampleLet’s imagine our Component is Counter. useReducer here in the below code accepts as arguments a reducer function, and an initial state value.  const Counter = () => { const [state, dispatch] = useReducer(reducer, 0)}In this case our state is an integer, which starts from 0:The reducer is a function that takes the current state and an action, which can be a value of any type you want. In this example it’s a string:const reducer = (state, action) => { switch (action) { case 'INCREMENT': return state + 1 case 'DECREMENT': return state - 1 default: throw new Error() } }We can use JSX to make this simple component work as below:const Counter = () => {const [count, dispatch] = useReducer(reducer, 0) return ( Counter: {count} dispatch('INCREMENT')}>+ dispatch('DECREMENT')}>- ) } This state can be an object with 'n’ number of properties, but different actions only change one property at a time.Putting up all this together, our Babel will look like:const { useReducer } = React const reducer = (state, action) => { switch (action) { case 'INCREMENT': return state + 1 case 'DECREMENT': return state - 1 default: throw new Error() } } const Counter = () => { const [count, dispatch] = useReducer(reducer, 0) return ( Counter: {count} dispatch('INCREMENT')}>+ dispatch('DECREMENT')}>-  ) } ReactDOM.render(, document.getElementById('app')) You should get the below output:Example2: Let’s see another TODO example. To show list of items:It was not possible to change the state of an item with the handler function earlier. But however, we can now do so, for example if we need to make the list of items stateful we can do so by using them as initial state for our useReducer hook by defining  reducer function:Consider the following JSX snippet for reducer:import React from 'react'; const initialTodo = [...]; const todoReducer = (state, action) => {  switch (action.type) { case 'DO_TODO':      return state.map(todo => { if (todo.id === action.id) { return { ...todo, complete: true }; } else { return todo; } }); case 'UNDO_TODO': return state.map(todo => { if (todo.id === action.id) { return { ...todo, complete: false }; } else { return todo; } }); default: return state; } }; const App = () => { const [todos, dispatch] = React.useReducer( todoReducer, initialTodo ); const handleChange = () => {}; return ( {todos.map(todo => ( ... ))} ); }; export default App; Now we can use the handler to dispatch an action for our reducer function.  Because we need the id as the identifier of a todo item in order to toggle it,  we can pass the item within the handler function by using a encapsulating arrow function as below:const handleChange = todo => { dispatch({ type: 'DO_TODO', id: todo.id }); }; And input will look like: handleChange(todo)} />Let's now implement to check our handler whether a todo item is completed or not by the below condition:const handleChange = todo => { dispatch({ type: todo.complete ? 'UNDO_TODO' : 'DO_TODO', id: todo.id, }); }; Putting up all this together, our component looks like:import React from 'react'; const initialTodo = [ { id: 'a', task: 'Do Something', complete: false,   }, { id: 'b', task: 'Walk over here', complete: false, }, ]; const todoReducer = (state, action) => { switch (action.type) { case 'DO_TODO': return state.map(todo => { if (todo.id === action.id) { return { ...todo, complete: true }; } else { return todo; } }); case 'UNDO_TODO': return state.map(todo => { if (todo.id === action.id) { return { ...todo, complete: false }; } else { return todo; } }); default: return state; } }; const App = () => { const [todos, dispatch] = React.useReducer( todoReducer, initialTodo ); const handleChange = todo => { dispatch({ type: todo.complete ? 'UNDO_TODO' : 'DO_TODO', id: todo.id, }); }; return ( {todos.map(todo => ( handleChange(todo)} /> {todo.task} ))} ); }; export default App; And here is the Output:Now the biggest question is:When do we use React.useReducer instead of React.useState? The answer is very simple and I will try to keep it even more simple:We can Use React.useReducer when -----Your application architecture is complex and big in size  When the logic to update state is super complex or you want to update state deep down in your component treeThe state value is either an object or an arrayYou need a more predictable, and maintainable state architecture of the applicationAnd, we can Use React.useState when -----Your application is smallThe state value is a primitive valueSimple UI state transitionsLogic is not complicated and can stay within one componentConclusionThe useReducer hook is a nice addition to the React library which allows for a  simpler, predictable and organized way to update our component’s state and makes sharing data between components a bit easier.It lets you optimize the performance of the components that trigger deep updates because now you can easily pass dispatch down instead of typical callbacks.And even if you take nothing else from this article, you should at least remember this: that useReducer allows us to define how we update our state value.Happy coding!
3490
Understanding the React useReducer Hook

IntroductionThe introduction of Hooks in React bro... Read More

How to Install Angular 10 on MacOS

Angular 10 is the latest version in the Angular family. Angular applications are basically designed for Single Page Applications (SPAs), where all controls are required in single page architecture. Angular is an application-based design framework, which provides the Cross-Platform development environment for creating the most sophisticated SPAs. These SPAs are efficient enough for giving us a component to view the model environment, making it an MVC or MVVM application. Angular provides a Progressive Web App architecture, which means that an application made in Angular gives us an App like experience with high-performance. Angular has zero-step installation, making its up- gradation using modern web capabilities possible, even if offline. Angular has the capability of making cross platform Desktop Apps. These can be created using MAC, Windows, or Linux OS using the same Angular methods. Angular can be rendered in Node.js, Microsoft .Net, PHP and many other servers by giving the output in HTML-CSS format. This even optimizes the App for SEO. Angular framework turns our templates into JavaScript Virtual machine codes which are highly optimized. With Angular CLI, the Command Line tools, we can build and deploy apps faster than ever before. Angular uses Karma for unit tests and Protractor for scenario tests, making the applications made in Angular more stable. Introduction: In this Article we are going to talk about how to install Angular 10 in MAC OS.  We will be covering the following contents:  Pre-requisites The Pre-requisites for installation Download and Install Node.js The Download Site Address  Instructions to Install Node.js Test Installation of Node.js Install Angular CLI How Node.js helps in installing Angular CLI Testing the installation of Angular CLI Create New Angular Application A Basic Hello-World Application in Angular  Serve Angular Application Running the Hello-World Application Check the Output Check the Browser for the Output Conclusion  Pre-requisites: Mentioned below are the pre-requisites for the installation of Angular in MAC OS. The Pre-requisites are: MAC OS->10.10 plus installed in your PC At least 4 GB RAM A Hard drive memory of 10 GB free Administrator account for installing software in MAC OS or User account with privilege to install and unrestricted access to all related websites for Node.js and Angular. Download and Install Node.js Node.js is an open-source software which is used to run JavaScript code outside a browser. Node.js is cross-platform making it suitable for major operating systems. It helps developers to use JavaScript in Network Applications, Command Line Tools, normal Web Applications, Web APIs, and more. It provides Dev Tooling local Web Server for live reloading and development experience. Thus, Node.js is an Open-Source Server environment that allows developers to run JavaScript on the server. So, before installing Angular 10, we need to install Node.js in the System. Download Node.js Open the following site in the browser: https://nodejs.org/en/download/ (Download the Node.js source code or a pre-built installer for your platform, and start developing today). We get the site as follows: Download the LTS version of the software with the latest features. This gives us three versions for different operating systems: Windows Installer (.msi) :  32-bit (node-v14.15.0-x86.msi) 64-bit (node-v14.15.0-x64.msi) Windows Binary (.zip) 32-bit (node-v14.15.0-x86.zip) 64-bit (node-v14.15.0-x64.zip) macOS Installer (.pkg) 64-bit (node-v14.15.0.pkg) macOS Binary (.tar.gz) 64-bit (node-v14.15.0-darwin-x64.tar.gz) Linux Binaries (x64) 64-bit (node-v14.15.0-linux-x64.tar.xz) Linux Binaries (ARM) ARMv7 (node-v14.15.0-linux-armv7l.tar.xz) ARMv8 (node-v14.15.0-linux-arm64.tar.xz) Source Code node-v14.15.0.tar.gz SmartOS Binaries 64-bit (node-v14.15.0-sunos-x64.tar.xz) Docker Image Official Node.js Docker Image  Linux on Power LE Systems 64-bit (node-v14.15.0-linux-ppc64le.tar.xz) Linux on System z 64-bit (node-v14.15.0-linux-s390x.tar.xz) AIX on Power Systems 64-bit (node-v14.15.0-aix-ppc64.tar.gz) Download the macOS Installer (.pkg) : 64-bit (node-v14.15.0.pkg). This is the latest version of Node installable package. Install the .pkg in your operating system by clicking on the installer.  Once clicked, the .pkg file opens the installer wizard. Click on continue to move to the next page. Click on continue to continue to the next page with License Terms and Conditions.   You will be asked to accept the license, please do so by clicking on Agree, after reading the terms and conditions. Click on Continue to move to the next page.  Once you have clicked on continue, you will get the install now page:  Click on Install, and enter the login credentials, the username and password, and then click on Install Software:  Once successfully installed, Node.js shows the following summary of the installation:  Click on Close to close the wizard. Set the /usr/local/bin in your $PATH so that you can access the node and npm executable files. To verify the same open the terminal and type: Echo $PATH Test Installation of Node.js Once the package is installed, open the Terminal and type the following command: node –v You will get the version of Node.js displayed. v14.15.0 and  npm –v You get the version of npm displayed. 6.4.1 Install Angular CLI Angular CLI has a wide range of commands for Angular Applications. It helps us in managing, testing, and building Angular applications. Once Node.js is installed in our system, we can use npm to install software globally on our system. Use –g option in the npm command to install the Angular CLI tool globally. Once done so it will be accessible to all users and applications on the mac OS system.  To install Angular CLI with the Node.js npm tool, use the following command: $ sudo npm install -g @angular/cli This command will install the latest Angular CLI version available at Angular site on your macOS system.  If you require other than the latest version of Angular, then use the following command in your mac OS: For Angular 6: $ npm install -g @angular/cli@6#Angular 6 For Angular 7: $ npm install -g @angular/cli@7         #Angular 7 For Angular 8: $ npm install -g @angular/cli@8         #Angular 8 For Angular 9: $ npm install -g @angular/cli@9         #Angular 9 Testing the installation of Angular CLI Once the installation is successful, Angular CLI will provide a command ng to be used for command line operations.  Type the following command to check the version of Angular CLI: $ ng --version   Or $ ng version And we should get the following output:  This completes your Angular installation. Now let us make a “Hello World” Application in Angular. Following section describes how to make a basic application in Angular. Create New Angular Application Create a folder for your application in the desired location on your system and open it on your favorite file browser.  A Basic Hello-World Application in Angular  Open a new terminal and move to your folder created for the application and type in the following command to create your app folder using ng create command as below.  $ ng create hello-world Or $ ng new hello-world For the Query “Would you like to add Angular Routing?” type Yes. For the Query “Which style sheet format would you like to choose?” move your cursor to point to “CSS” and click enter. Then it would take some time for further installation of the application folder, so we need to have patience in this respect. At last, when the command is executed successfully, Angular creates a skeleton application under the folder. It also includes a bunch of files and other important necessities for the application. Serve Angular Application Once our Hello-World project is created change the current directory to project directory by cd command and run application using ng serve command as shown below: $ cd hello-world  $ ng serve We can leave the ng serve command running in the terminal as it will automatically refresh the browser each time we make and save changes in our Angular application. This makes Angular development quick and iterative. Running the Hello-World Application Once run, you can access your Angular application on localhost port 4200, which is the default host and port used by any Angular application. To get the output, type in your favorite browser, address bar the following: http://localhostž4200 If another application is running on that address, you can simply run the command. $ ng serve--port It will generate a different port for you to navigate to through the web browser.  Check the Output Typically, the browser looks something like this: Conclusion Through Angular 10 we can develop very dynamic applications. However, sometimes we may require to undo the installation of Angular CLI. We can uninstall angular cli through command terminal by using the npm tool. Run the following command in the terminal to Uninstall Angular: $ npm uninstall -g @angular/cli Angular applications are still SPAs or Single Page Applications in their Core. The loading of the Application is still triggered by a main request to the server. The command ng serve helps us to serve this request every time we make changes to our scripts. As our HTML or JavaScript changes, so does the new server request, sending the new changed response to the web browser. 
5926
How to Install Angular 10 on MacOS

Angular 10 is the latest version in the Angular... Read More