Web Application Development Archives - TatvaSoft Blog https://www.tatvasoft.com/blog/category/web-application-development/feed/ Thu, 01 May 2025 08:30:07 +0000 en-US hourly 1 React vs Angular: Covering Every Aspects https://www.tatvasoft.com/blog/react-vs-angular/ https://www.tatvasoft.com/blog/react-vs-angular/#respond Wed, 05 Feb 2025 08:37:05 +0000 https://www.tatvasoft.com/blog/?p=13750 Both React and Angular are robust JavaScript frameworks for front-end web development. So, the debate of React vs Angular is always on the table when designing user interfaces for web projects. This has also confused companies regarding whether to hire Angular developers or collaborate with a React development company for their projects.

The post React vs Angular: Covering Every Aspects appeared first on TatvaSoft Blog.

]]>

Key Takeaways

  1. React is known for its component-based architecture which, developers use to build lightweight and faster applications.
  2. Angular is a popular web development framework with a robust structure, and its rich built-in features make it an ideal choice for creating large-scale apps.
  3. React supports a plethora of third-party integrations, while Angular offers a wide range of built-in functionalities.
  4. Both have strong community support.
  5. The choice depends on project needs: React for speed, and Angular for scalability.
  6. Developer preferences: Angular for maintainability, React for fast updates.

Both React and Angular are robust JavaScript frameworks for front-end web development. So, the debate of React vs Angular is always on the table when designing user interfaces for web projects. This has also confused companies regarding whether to hire Angular developers or collaborate with a React development company for their projects.

To make informed decisions, companies evaluate vendors and interview developers before hiring them to understand their experience and expertise. Similarly, you have to know your technologies before you use them in your project.

Angular is one of the most popular JavaScript frameworks offering templates or a foundation for developers to build UI components whereas React is a JavaScript library providing predefined code snippets for standardized and rapid development. Both have unique and diverse offerings with their own set of advantages and disadvantages. You have to compare your options and weigh them against your requirements.

This article not only covers a detailed comparison and use cases like every other comparison blog on Angular vs React but also provides a guide for developing sample apps in both technologies. This will give you an idea of the viability of the practical implementation of each option. Let’s get started.

1. Angular vs React: A Detailed Comparison

In this section, we will compare Angular and React in detail against the basic parameters of software development.

1.1 Server-Side Rendering

Angular renders a static view for your app before making it entirely interactive with the help of server-side rendering. It enhances the performance on the server side and reduces traffic between the client and server by using client-side caching with JSON. 

You must implement React server-side rendering to make your app SEO-friendly. This Javascript library has some specific functions that can help you with the process. It allows you to render your app by calling the RenderToString function instead of the Render function. React is quite flexible, unlike other rigid JavaScript libraries. 

If you prefer not to create DOM attributes for a simple static page generator then React allows you to use renderToStaticMarkup. Facebook is a notable example of a React app with high-speed rendering. It functions completely well even on modest internet connections. 

1.2 Performance

React comes with virtual DOM trees. They are lightweight and not built on the server. Therefore, there is less data to load for the browser, resulting in improved runtime performance. Moreover, the unidirectional flow of information reduces the overall workload in the React apps. 

But Angular is different, it has a bi-directional flow and every two-way data binding process needs a watcher to monitor the changes. Unless all the watchers are confirmed, every loop remains. This might hurt the performance of the Angular application. 

1.3 Component Architecture: Container and Presentation Components

Angular 

Container components are used to fetch data and interact with services whereas the presentation components are the ones to whom the data is fed. See the container component example given below, the services are injected into the component to load some data. 

@Component({…})
export class UsersComponent implements OnInit{
  users: User[];
 
  constructor(private userService: UserService,
             ) {
  }
  ngOnInit(): void {
    this.userService.getAllUsers().subscribe((data) => {
      this.users = data;
    });
  }
  addUser(user: User) {
    this.userService.addUser(user)
      .subscribe(() => alert(`User Created Successfully.`));
  }
}

Its template will now represent two different presentation components. 



Often referred to as smart, these components leverage services to get data and help business logic to transpire. They can pass the data to child components since they represent them. Container components have just one instance in the entire app. And being tied to the context they are used in, they are hardly reused. 

Now, let’s take a look at the example of the presentation component.

@Component({...})
export class UserListComponent {
  @Input()
  user: User;
  @Input()
  buttonText: string;
  @Output()
  onButtonClick = new EventEmitter();
}

Presentation components are pure and simple UI components. They only require some input data to render. An HTML template for this component looks like. 

{{user.title}}

{{user.name}}

{{user.email}}

Presentation components are nothing but an HTML template that you need to fill out with necessary data. You can easily reuse these components in your application. A typical illustration of the component architecture is given below. 

Angular Component Architecture

The container components retrieve the data from services and use the two-way data binding or @input() to pass this data to its child presentation components. Whenever a significant event occurs like clicking a button, the presentation component notifies the parent container component of the event. In response, the container components implement an appropriate action. 

Despite having a single goal to render the template properly, presentation components are independent of their runtime context. This allows developers to reuse them in their applications.

React

The presentation component decides how the data should be displayed on the screen whereas the container component decides which data should be displayed to the user. 

The presentation component receives callbacks and the necessary data through props but doesn’t have any connection with the data specifications outside the component. It has a DOM markup and styles of its own. There are no major dependencies on the rest of the application because of this component. The code given below is of the presentation component that is focused on showing an element. The props have provided it with the required data. 

import React from "react";

// Presentational component
const Users = () => {
  return (
    
{users.map((user) => (

UserDetails

Name: {user.name}

Username: {user.username}

Email: {user.email}

Phone: {user.phone}

Company

Company Name: {user.company.name}

))}
); }; export default Users;

The container components manage how things work. It doesn’t have its own markup and DOM. It provides data, behavior, and callbacks to the presentation components. 

import React, { useState, useEffect } from "react";
import axios from "axios";

// Container component
const UsersContainer = () => {
  const [users, setUsers] = useState([]);
  useEffect(() => {
    // Fetch users data after the component mounts
    axios.get("https://jsonplaceholder.typicode.com/users")
      .then((response:any) => {
        setUsers(response.data);
      })
      .catch((error) => {
        console.error("There was an error fetching users!", error);
      });
  }, []); // Empty dependency array ensures the effect runs once on mount

  return ;
};
export default UsersContainer;

1.4 State Management

Managing the state of the UI components, such as text fields and radio buttons, can be challenging. Angular offers a state management library called NGRX that enables reactive state management. It follows the principles of FLUX/REDUX. NGRX stores all the states in a single tree, giving you access to forms across the entire application.

State Management

Every component in React has its own state. Therefore, you have to separately handle these components. Otherwise, React developers may encounter a large number of unexpected errors and bugs in a large-scale project. 

React offers multiple options for state management. So, if you don’t want to use state management libraries like Redux and Recoil, you can simply manage the state using Hooks.

1.5 Community and Ecosystem Support

One of the major benefits of using Angular is its extensive ecosystem and strong community support. It can assist with troubleshooting and offer support through learning materials like blogs, tutorial videos, templates, and sample projects. 

Angular ecosystem consists of a large number of third-party tools and libraries that can provide additional components, functionalities, and utilities to integrate into your app. Angular Material for UI components ngx-translate for internationalization, and NgRx for state management are some of the popular component libraries contributed by the Angular community. 

React is an open-source JavaScript library. It has a large and supportive community along with an ecosystem providing a wide range of third-party tools and libraries. They are quite helpful in extending the functionality and enhancing the performance of the application. 

Some of the notable tools include CSS modules for styling, Formik for form validation, React Router for routing, and MobX and Redux for state management. React is used for building various JavaScript frameworks and libraries that have become popular nowadays. 

1.6 Data Binding

Angular comes with two-way data binding, which means the states will be automatically updated when any changes are implemented in any element of the user interface. In short, the same data is used to update both layers. This helps developers create interactive user interfaces without putting in extra effort or making several callbacks. Two-way data binding works effectively to fulfill the complex requirements of large enterprise software.

React has one-way data binding. So the changes are done in the interface after updating the model state. Similarly, the model state isn’t updated when changes are implemented in the user interface. With uni-directional flow, React developers have more control over their web and mobile applications. 

The lack of real-time updates forces developers to handle the complex details of the objects when using React. However, this problem can be resolved by using two-way data binding helpers along with React’s one-way data binding to simplify the parsing and extensive data manipulation.

1.7 Computed Properties

Angular

Despite the fact that Angular doesn’t have any decorator or computed keyword, there are many ways Angular can define computed properties. One of them is RXJS. The code given below shows how Angular uses the RxJS approach to define computed properties. 

interface User {
  id: number;
  name: string;
  active: boolean;
}

@Component({
  selector: 'user-stats',
  template: `
    

User Statistics

Active Users: {{ activeCount$ | async }}

` }) export class UserStatsComponent { users$ = new BehaviorSubject([]); activeCount$ = this.users$.pipe( map(users => users.filter(user => user.active).length) ); updateUsers(users: User[]) { this.users$.next(users); } }

users$ (BehaviorSubject): It is a data source with a list of users that needs to be observed. 

activeCount$ (Computed Property): This observable uses the RxJS’s map operator to compute the total number of active users. The computed value of the activeCount$ automatically gets updated every time a change is observed in the user$ subject. 

This way of defining the computed properties is also identified as a reactive approach. RxJS is quite powerful with out-of-the-box operators. Although the example we considered above is a simple one, RxJS can also help write clean code for complex logic. If any part of the state is already managed with RxJS then it is recommended that you use this approach. 

React

React offers a very simple solution for this.

import {  makeAutoObservable } from 'mobx';
import {observer} from 'mobx-react';
import React, { Component } from 'react';
 
'

export class AppStore {
constructor() {
    makeAutoObservable(this);
  }
userName = "";

   onUsernameChange = (event) => {
    this.userName = event.target.value;
  };
}
 
export class HomeStore {
constructor() {
    makeAutoObservable(this);
  }
   counter = 0
  increment = () => {
    this.counter++
  };
   get counterMessage() {
    console.log('recompute counterMessage!')
    return `${this.counter} ${this.counter === 1 ? 'click' : 'clicks'} since last visit`
  };
}
function Input ({ type, label, name, value, onChange }) {
return (
    
); }

A computed property binds to the counter and returns a properly pluralized message. Whenever the counter changes, the result of the counterMessage should be cached and recalculated. 

const Home = observer(({appStore, homeStore}) => {
return (
{homeStore.counterMessage}
); }); export default function App() { const homeStore = new HomeStore(); const appStore = new AppStore(); return ; }

The increment method and property are referenced from the JSX template. You can drive the input field by allowing the appStore’s method to manage user events and bind them to a value. 

1.8 Form Validations

In the case of form validation, there is a difference in React and Angular’s approaches. Angular uses built-in validators or creates custom validators to validate the forms. These validators can be added to the entire form or to individual form controls depending on the specific requirements. 

They help check regular expressions, maximum and minimum length, and required fields. In case of errors, Angular provides default error messages to display on the user interface. 

There are two techniques to validate a form in Angular: Template-driven form validation and Reactive form validation. 

Template-driven Form Validation

In this Angular Form Validation method, we will use the directives from Angular templates to define and validate the form. This approach is an ideal option to validate simple forms. 

import { Component } from '@angular/core';

@Component({
  selector: 'app-root',
  template: `
    
Username is required. Username must be at least 3 characters long.
Email is required. Enter a valid email.
`, }) export class AppComponent { onSubmit(form: any) { console.log(form.value); } }

Reactive Form Validation

Reactive form validation in Angular is more of a programmatic approach that helps define and validate complex forms. 

import { Component } from '@angular/core';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';

@Component({
  selector: 'app-root',
  template: `
    
Username is required. Username must be at least 3 characters long.
Email is required. Enter a valid email.
`, }) export class AppComponent { userForm: FormGroup; constructor(private fb: FormBuilder) { this.userForm = this.fb.group({ username: ['', [Validators.required, Validators.minLength(3)]], email: ['', [Validators.required, Validators.email]], }); } onSubmit() { console.log(this.userForm.value); } }

Both Angular form validation methods discussed here are widely used but the decision of picking a suitable way boils down to the complexity of the form. If you are working with a simple form then use the template-driven form validation technique. But if you want better control and scalability then use reactive form validation. 

React creates custom validation functions or leverages third-party libraries to achieve form validation. It doesn’t come with a built-in form validation, React developers are responsible for handling the validation logic. Form validations are tracked and error messages are displayed using the state and setState functions. 

The code given below shows the use of a custom validation function from React. 

import React, { useState } from "react";

const MyForm = () => {
  const [firstName, setFirstName] = useState("");
  const [lastName, setLastName] = useState("");
  const [email, setEmail] = useState("");
  const [errors, setErrors] = useState({});

  // Validate form function
  const validateForm = () => {
    let errors = {};
    if (!firstName) {
      errors.firstName = "First name is required";
    }
    if (!lastName) {
      errors.lastName = "Last name is required";
    }
    if (!email) {
      errors.email = "Email is required";
    } else if (!/\S+@\S+\.\S+/.test(email)) {
      errors.email = "Email is invalid";
    }
    setErrors(errors);
    return Object.keys(errors).length === 0;
  };

  // Handle form submission
  const handleSubmit = (event) => {
    event.preventDefault();
    if (validateForm()) {
      // handle form submission (e.g., send data to server)
      console.log("Form submitted successfully");
    }
  };

  // Handle input change
  const handleChange = (event) => {
    const { name, value } = event.target;
    if (name === "firstName") {
      setFirstName(value);
    } else if (name === "lastName") {
      setLastName(value);
    } else if (name === "email") {
      setEmail(value);
    }
  };
  return (
    
{errors.firstName &&
{errors.firstName}
} {errors.lastName &&
{errors.lastName}
} {errors.email &&
{errors.email}
}
); }; export default MyForm;

In the above example, the validation state of the form is checked with the validateForm function. The error objects are used to track the validation errors and display the error messages to the users. 

1.9 Routing

Routing helps provide a better user experience. When the user clicks on any button or element or enters any URL, routing facilitates movement between different parts of the app. Routing gives a new functionality for navigating to the detailed view of every to-do item in your app. For instance, when a user clicks on the to-do item from the list, the app will route them to a new page displaying the item’s title and its completion status. 

Angular Routing

Angular Router is the built-in routing solution in this development framework. It helps Angular developers create dynamic and high-performance applications by offering routing features like lazy loading, route guards, and nested routes. 

Angular Path-Based Routing

Angular simplifies the routing process by allowing you to define the routes using path URLs. So, Angular would render the component every time a user navigates to the corresponding URL. 

We can define appRoutingModule and add a path for the corresponding component like the below code.

const routes: Routes = [
	{ path: '', component: HomeComponent },
	{ path: 'about', component: AboutComponent }
];
@NgModule({ 
imports: [RouterModule.forRoot(routes)], 
exports: [RouterModule] 
}) 
export class AppRoutingModule {}

Then we need to import AppRoutingModule in App.module file

We will now use lazy loading for Angular routing. Once implemented, it will allow the feature module to load only when it’s necessary. As a result, the app’s performance will improve. This technique can come in handy when handling large apps.

Steps to Implement:

  • Create feature modules.
  • Configure lazy loading in the routing module using the loadChildren property.
  • Define routes in the feature module’s routing module.

In AppRouting we can define a path for the particular module as shown below

const routes: Routes = [ 
{ path: 'feature', loadChildren: () => import('./feature/feature.module').then(m => m.FeatureModule) } 
];

Angular supports nested routes, where one component has its own child routes. Child routes are defined inside the parent route.

const routes: Routes = [ 
{ path: 'parent', component: ParentComponent, 
children: [ 
{ path: 'child', component: ChildComponent } 
] 
} 
];

We can add Guards to protect routes and Query parameters and fragments for additional information.

Guards

const routes: Routes = [
 { path: 'profile', component: ProfileComponent, canActivate: [AuthGuard] } 
];

Query Parameters

this.router.navigate(['/home'], { queryParams: { page: 1, sort: 'asc' } });

React Routing

A wide range of routing libraries are available in React. Here we are going to use React Router on a basic React app with four major components including the Home, About, Contact, and NotFound. 

With the help of an App component, all four of these components are imported into the file and then executed. Using React Router helps arrange for a seamless transition between these components. 

import React from 'react';
import { BrowserRouter as Router, Route, Switch, Link } from 'react-router-dom';
Import Dashboard from ‘./components/Dashboard;
Import Services from ‘./components/Services ;
Import ReachUs from ‘./components/ReachUs;
Import NotFound from ‘./components/NotFound;
Import ‘./App.css’;

const App = () => {
  return (
    
      
); }; export default App;

2. Sample App Development

Let’s have a look at the sample to-do application development using React and Angular respectively.

2.1 React

Prerequisites: The presence of Node.js and React is required in the system. 

Step 1: Create a React app with the following command.

npx create-react-app 

Step 2: Now, we will create components for our Todo application.

  1. Create a Todo Component which contains logic to list down the to-do items. 
  2. Create a Form component that contains logic to add a new task.
  3. Create a TodoList component that contains logic for Listing, Mark as Complete, and Delete the task.

Now, create a Todo.js file in components and write the following code in the same.

Create a Todo.js file in components and write the following code in the same. 

import React from "react";

const Todo = ({ text, todo, completeHandler, deleteHandler }) => {
  return (
    
  • {text}
  • ); }; export default Todo;

    Then create a Form.js file in components and write the following code in the same. 

    import React, { useState } from "react";
    
    const Form = ({ todos, setTodos }) => {
      const [todoText, setTodoText] = useState("");
    
      const handleSubmit = (e) => {
        e.preventDefault();
        setTodos([
          ...todos,
          { text: todoText, completed: false, id: Math.random() * 1000 },
        ]);
        setTodoText("");
      };
    
      return (
        
    setTodoText(e.target.value)} />
    ); }; export default Form;

    Let’s create a TodoList.js file in components and write the following code in the same. 

    import React from "react";
    import Todo from "./Todo";
    
    const TodoList = ({ todos, setTodos }) => {
      const deleteHandler = (id) => {
        setTodos(todos.filter((el) => el.id !== id));
      };
    
      const completeHandler = (id) => {
        setTodos(
          todos.map((item) => {
            if (item.id === id) {
              return {
                ...item,
                completed: !item.completed,
              };
            }
            return item;
          })
        );
      };
    
      return (
        
      {todos.map((todo) => ( ))}
    ); }; export default TodoList;

    Step 3: Now, open app.js file in src folder and Write the following code in the same.

    import React, { useState } from "react";
    import "./App.css";
    import Form from "./components/Form";
    import TodoList from "./components/TodoList";
    
    const App = () => {
      const [todos, setTodos] = useState([]);
    
      return (
        
    To-do List
    ); }; export default App;

    Step 4: Now add some CSS. Create an App.css file in the src folder and write the code to include CSS.

    * {
      margin: 0;
      padding: 0;
      box-sizing: border-box;
    } 
    body {
      background-image: linear-gradient(120deg, #f6d365 0%, #fda085 100%);
      color: white;
      font-family: "Poppins", sans-serif;
      min-height: 100vh;
    } 
    header {
      font-size: 3rem;
      padding-top: 4rem;
      font-weight: 600;
    } 
    header,
    form {
      min-height: 15vh;
      display: flex;
      justify-content: center;
      align-items: center;
    } 
    form input,
    form button {
      padding: 0.5rem;
      font-size: 2rem;
      border: none;
      background: white;
    } 
    form input:focus {
      outline: none;
    } 
    form button {
      color: #ff6f47;
      background: #f7fffe;
      cursor: pointer;
      transition: all 0.3s ease;
    } 
    form button:hover {
      background: #ff6f47;
      color: white;
    } 
    .todo-container {
      display: flex;
      justify-content: center;
      align-items: center;
    }
    .todo-list {
      min-width: 30%;
      list-style: none;
    } 
    .todo {
      margin: 0.5rem;
      background: white;
      font-size: 1.5rem;
      color: black;
      display: flex;
      justify-content: space-between;
      align-items: center;
      transition: all 1s ease;
    } 
    .todo li {
      flex: 1;
    } 
    .trash-btn,
    .complete-btn,
    .edit-btn {
      background: rgb(212, 11, 14) ;
      color: white;
      border: none;
      padding: 1rem;
      cursor: pointer;
      font-size: 1rem;
      width: 48px;
    }
    .complete-btn {
      background: #ff6f47 ;
    }
    .edit-btn {
      background: rgb(11, 212, 162);
    }
    .todo-item {
      padding: 0rem 0.5rem;
    }
    .fa-trash,
    .fa-check,
    .fa-times {
      pointer-events: none;
    }
    .fall {
      transform: translateY(10rem) rotateZ(20deg);
      opacity: 0;
    }
    .completed {
      text-decoration: line-through;
      opacity: 0.5;
    }
    .fa-pen { 
      font-size: 25px;
    }
    

    Step 5: Update the index.js and index.css files as per the mentioned repository. 

    Step 6: Update index.html file of public folder as per the mentioned repository.

    
    
        
    

    Step 7: Run the application using the following command. 

    npm start
    

    Step 8: A new window in the browser will pop up. Add a few tasks here.

    To-do List - React
    To-do List - React

    Folder Structure:

    Folder Structure - React

    2.2 Angular

    Prerequisites: Install Node and Angular CLI in your system. 

    Step 1: Create an Angular app with the following command.

    > ng new to-do-list 
    

    Move to the project directory using the following command.

    > cd to-do-list 
    

    Step 2: Create an interface for To-do items.

    export interface ToDoItem { 
      task: string; 
      isCompleted: boolean; 
    } 
    

    Step 3: Create 3 components in src folder using the following commands.

    > ng generate component todo  
    > ng generate component form 
    > ng generate component todolist
    
    1. Create a Todo Component which contains logic to list down the to-do items.
    2. Create a Form component that contains logic to add a new task 
    3. Create a TodoList component that contains logic for listing, mark as complete, and delete the task.

    1. ToDo component:

    This component is responsible for displaying individual to-do items along with a delete button and a checkbox to mark an item as complete. 

    template file: We have used a <p> to display the title, a check box to mark the completion of the task, and a delete button.

    {{ title }}

    Delete

    ts file: ts file contains 2 input properties that are title and isCompleted, along with this there is a delete method that emits the event to a parent component.

    import { Component, EventEmitter, Input, Output } from '@angular/core'; 
    import { CommonModule } from '@angular/common'; 
    @Component({ 
      selector: 'app-to-do', 
      standalone: true, 
      imports: [CommonModule], 
      templateUrl: './to-do.component.html', 
      styleUrl: './to-do.component.css', 
    }) 
    export class ToDoComponent { 
      @Input() title: string = ''; 
      @Input() isCompleted: boolean = false; 
      @Output() deleteTodoItem = new EventEmitter(); 
     
      onDelete(): void { 
        this.deleteTodoItem.emit(); 
      } 
    }
    

    2. to-do-list: display ToDo-list

    template file: use *ngFor directive to iterate each element in the toDoList.

    ts file: ts file takes to-do list as input and a delete method which emits the event to the parent component. 

    import { Component, EventEmitter, Input, Output } from '@angular/core'; 
    import { ToDoComponent } from '../to-do/to-do.component'; 
    import { CommonModule } from '@angular/common'; 
    import { ToDoItem } from '../../ToDoItem'; 
    @Component({ 
      selector: 'app-to-do-list', 
      standalone: true, 
      imports: [ToDoComponent, CommonModule], 
      templateUrl: './to-do-list.component.html', 
      styleUrl: './to-do-list.component.css', 
    }) 
    export class ToDoListComponent { 
      @Input() toDoList: ToDoItem[] = []; 
      @Output() deleteItem = new EventEmitter(); 
     
      deleteTodoItem(todoItem: any): void { 
        this.deleteItem.emit(todoItem); 
      } 
    } 
    

    3. Form component 

    Template file: contains an input element to store the value of the to-do task and an add button. 

    Add

    Ts file: There is a method to push an item to the parent component so that it can be added to a to-do list. 

    import { ToDoItem } from './../../ToDoItem'; 
    import { Component, EventEmitter, Output  } from '@angular/core'; 
    import { FormsModule } from '@angular/forms'; 
    @Component({ 
      selector: 'app-form', 
      standalone: true, 
      imports: [FormsModule], 
      templateUrl: './form.component.html', 
      styleUrl: './form.component.css', 
    }) 
    export class FormComponent { 
      @Output() addTodoItem = new EventEmitter(); 
     
      toDoItem: ToDoItem = { task: '', isCompleted: false }; 
     
      onAddTodoItem() { 
        this.addTodoItem.emit(this.toDoItem); 
        this.toDoItem = { task: '', isCompleted: false }; 
      } 
     
    }  
    

    4. App component:

    To-Do List


    Ts file: implement logic to add and delete items from the to-do list.

    import { Component } from '@angular/core'; 
    import { RouterOutlet } from '@angular/router'; 
    import { ToDoListComponent } from '../Components/to-do-list/to-do-list.component'; 
    import { FormComponent } from '../Components/form/form.component'; 
    import { ToDoItem } from '../ToDoItem'; 
    import { CommonModule } from '@angular/common'; 
    @Component({ 
      selector: 'app-root', 
      standalone: true, 
      imports: [RouterOutlet, ToDoListComponent, FormComponent, CommonModule], 
      templateUrl: './app.component.html', 
      styleUrl: './app.component.css', 
    }) 
    export class AppComponent { 
      title = 'todo-list-app'; 
      toDoList: ToDoItem[] = [ 
      ]; 
     
      addTodoItem(item: ToDoItem) { 
        this.toDoList.push(item); 
      } 
     
      deleteTodoItem(todoItem: any): void { 
        this.toDoList = this.toDoList.filter((item) => item !== todoItem); 
      } 
    } 
    

    Step 4: Now Add some CSS. Create an App.css file in the src folder and write the code to include CSS.

    Step 5: Run your application using the following command.

    npm start 
    

    Step 6: Test your application in the browser, by adding/deleting a task and marking the task as complete. 

    To-Do List - Angular
    To-Do List - Angular

    Folder Structure: 

    Folder Structure- Angular

    3. Best Practices Comparison of React vs Angular

    After comparing the Angular and React technologies with basic parameters and going through their development guides, it’s time to discuss their development best practices. Some practices are implemented with almost all technologies, the implementation of these practices may vary a little.

    3.1 Reusable Components

    Components in React are small, simple, self-contained, and function-specific. They are designed in a way that a single component either renders a specific section of the application or alters its behavior. This makes it easy to test and maintain React components, allowing for their reuse across different applications. Reusable React components that can perform standard functions for your app are available at community ReactJS development forums. 

    Such standard and reusable components are kept small and specific, which helps improve the performance of the application. Because they use minimal space in your project, it leaves room for innovation. Although some reusable components might take more space if their functions are complex but critical to the app. In such cases, you have to consider your requirements and proceed accordingly. 

    Building reusable components is an inherent practice in Angular development. It is based on the requirement of the same component at multiple places or in multiple instances. Reusable components in Angular maintain consistent performance and functionality throughout the application. Even in the case of redesigning, you don’t need to rewrite all of your components when you have reusable ones at your disposal. 

    3.2 Component Communication

    Here, we are discussing component communication between parent to child, child to parent, and sibling components in Angular and React.

    Angular: Parent to Child

    Using the input decorator, we can pass data from the parent component to the child component in Angular. The code given below uses an input decorator to pass data from the parent component to the child component. 

    Parent component- Here we are sending a text message from the parent.

    parent.component.ts

    @Component({
      selector: 'app-parent',
      templateUrl: './parent.component.html',
      styleUrl: './parent.component.css',
    })
    export class ParentComponent {
      responseMessage = 'Message From Parent';
    } 
    

    In the Angular child component, the text message is passed by property binding. To modify the text message, we have to use the input text box from the parent component. 

    Parent.component.html

    Parent

    Child component- Here we will have an @Input decorator which will be used in the parent to send data.

    child.component.ts

    @Component({
      selector: 'app-child',
      templateUrl: './child.component.html',
      styleUrl: './child.component.css',
    })
    export class ChildComponent {
      @Input() message: string | null = null;
    }
    

    Using interpolation binding in the code below, we can display the text message. If it is updated in the parent component then it will be automatically updated in the child component as well. 

    Child.component.html

    Child

    Message : {{ message }}

    Output:

    PArent to Child Output - Angular

    Angular: Child to Parent

    In Angular, the @Output decorator is used for communication from the child to the parent component. 

    Child component- The child component uses EventEmitter to emit events and data to the parent component. The @Output decorator is used to expose the Event Emitter which allows the parent component to list and handle emitted events.

    child.component.ts

    @Component({
      selector: 'app-child',
      templateUrl: './child.component.html',
      styleUrl: './child.component.css',
    })
    export class ChildComponent {
      @Output() changeMessage = new EventEmitter();
    }
    Child.component.html
    

    Child

    Parent Component

    parent.component.ts

    @Component({
      selector: 'app-parent',
      templateUrl: './parent.component.html',
      styleUrl: './parent.component.css',
    })
    export class ParentComponent {
      responseMessage = '';
    
      updateMessage(e: any): void {
        this.responseMessage = e;
      }
    }
    

    To update the message in the parent component, we use an output decorator named changeMessage in the code below. 

    Parent.component.html

    Parent

    Message : {{ responseMessage }}

    Output:

    ChildtoParentOutput-Angular

    Angular: Passing Data between Siblings

    There are multiple ways to share data between sibling components,

    1. Using RxJS (common and recommended approach).
    2. Using the parent component as a mediator.
    3. Using State management.
    4. Using Local or Session storage.
    5. Using Angular Routing.

    We can create a service that acts as a shared data store.

    Use Subject or BehaviorSubject from RxJS, which is recommended to share data reactively.

    shared-data.service.ts

    This service will have a behaviorSubject from the RxJS library that used to store the current value and emit it to new subscribers

    import { Injectable } from '@angular/core';
    import { BehaviorSubject } from 'rxjs';
    
    @Injectable({ providedIn: 'root' })
    export class SharedDataService {
      private data = new BehaviorSubject<{ message: string; from: string }>({
        message: '',
        from: '',
      });
      sharedData$ = this.data.asObservable();
    
      setData(newData: { message: string; from: string }) {
        this.data.next(newData);
      }
    
      getData() {
        return this.data;
      }
    }
    

    Child 1 component- With this code, we inject the SharedDataService and check if the message is from the child 2 component before it is updated. Once the message is updated through changeMessage, it is sent to the child 2 component.

    child1.component.ts

    @Component({
      selector: 'app-child',
      templateUrl: './child.component.html',
      styleUrl: './child.component.css',
    })
    export class ChildComponent implements OnInit {
      message: string = '';
    
      constructor(private sharedService: SharedDataService) {}
    
      ngOnInit(): void {
        this.sharedService.getData().subscribe((data) => {
          if (data.from == 'c2') this.message = data.message;
        });
      }
    
      changeMessage(msg: string): void {
        this.sharedService.setData({ message: msg, from: 'c1' });
      }
    }
    

    child1.component.html

    Child 1

    Message From Child 2: {{ message }}

    Child 2 component- The code below injects the ShareDataService and checks if the message is from the child 1 component before it is updated. The message is sent to the child 1 component after updating it with the changeMessage. 

    child2.component.ts

    @Component({
      selector: 'app-child2',
      templateUrl: './child2.component.html',
      styleUrl: './child2.component.css',
    })
    export class Child2Component implements OnInit {
      message: string = '';
    
      constructor(private sharedService: SharedDataService) {}
    
      ngOnInit(): void {
        this.sharedService.getData().subscribe((data) => {
          if (data.from == 'c1') this.message = data.message;
        });
      }
    
      changeMessage(msg: string): void {
        this.sharedService.setData({ message: msg, from: 'c2' });
      }
    }
    

    child2.component.html

    Child 2

    Message From Child 1: {{ message }}

    Output:

    Sibling component output - Angular

    React: Parent to Child Communication

    Parent components in React applications use a special property called Props to communicate with the child components. HTML attributes are leveraged to pass props that are read-only from parent-to-child components. Let’s look at an example to understand this.

    ParentComponent.tsx

    import React, { useState } from "react";
    import ChildComponent from "./ChildComponent";
    const styles: { [key: string]: React.CSSProperties } = {
      parentContainer: {
        backgroundColor: "#0078FF",
        display: "flex",
        flexDirection: "column",
        justifyContent: "flex-start",
        alignItems: "flex-start",
        color: "white",
        padding: "10px",
      },
      parentContent: {
        marginBottom: "20px",
        width: "100%",
      },
      parentHeader: {
        fontSize: "3rem",
      },
      input: {
        padding: "15px",
        width: "30%",
        borderRadius: "8px",
        border: "2px solid white",
        fontSize: "1.2rem",
      },
    };
    const ParentComponent: React.FC = () => {
      const [message, setMessage] = useState("message from parent");
      return (
        

    Parent

    { setMessage(e.target.value); }} style={styles.input} placeholder="Type a message..." />
    ); }; export default ParentComponent;

    Child component- Here we will have received a message from the parent component as props.

    ChildComponen.tsx

    import React from "react";
    const styles: { [key: string]: React.CSSProperties } = {
      childContainer: {
        backgroundColor: "green",
        color: "white",
        borderRadius: "10px",
        width: "100%",
        marginTop: "20px",
        textAlign: "center",
      },
      childHeader: {
        fontSize: "3rem",
        marginBottom: "10px",
      },
      childMessage: {
        fontSize: "1.2rem",
      },
    };
    interface ChildProps {
      message: string;
    }
    const ChildComponent: React.FC = ({ message }) => {
      return (
        

    Child

    Message: {message}

    ); }; export default ChildComponent;

    Open App.tsx file in src folder and modify the following code in the same.

    import React from "react";
    import "./App.css";
    import ParentComponent from "./components/ParentComponent";
    const App = () => {
      return ;
    };
    export default App;
    

    Run the application using the following command. 

    npm start
    

    Output:

    Parenttochild output_React

    React: Child to Parent Communication

    For child-to-parent communication in React, a callback function is passed as a prop from parent to child component. Whenever the child wants to communicate with the parent, it has to call this function.

    Child component- Whenever the child component needs to send some data or trigger an event, it just has to call the function passed to it from the parent.

    ChildComponent.tsx

    import React from 'react'
    interface ChildComponentProps {
        setMessage?: (value: string) => any;
    }
    const styles: { [key: string]: React.CSSProperties } = {
        childContainer: {
            backgroundColor: "green",
            color: "white",
            borderRadius: "10px",
            textAlign: "center",
            padding: "20px",
        },
        childHeader: {
            fontSize: "3rem",
            margin: "10px",
        },
        input: {
            padding: "15px",
            width: "30%",
            borderRadius: "8px",
            border: "2px solid white",
            fontSize: "1.2rem",
        },
    };
    const ChildComponent: React.FC = ({ setMessage }) => {
        const [responseMessage, setResponseMessage] = React.useState('');
        return (
            

    Child

    { setResponseMessage(e.target.value) setMessage?.(e.target.value); }} style={styles.input} placeholder="Type a message..." />
    ) } export default ChildComponent

    Parent Component- The parent component renders the ChildComponent and passes the setMessage function to it through the setMessage prop.

    The parent also displays the response message it receives from the child.

    ParentComponent.tsx

    import React from 'react'
    import ChildComponent from './ChildComponent'
    
    const styles: { [key: string]: React.CSSProperties } = {
        parentContainer: {
            backgroundColor: "#0078FF",
            color: "white",
            padding: "10px",
        },
        parentContent: {
            marginBottom: "20px",
            width: "100%",
        },
        parentHeader: {
            fontSize: "3rem",
        },
        MessageText: {
            fontSize: "1.2rem",
        },
    };
    const ParentComponent = () => {
        const [responseMessage, setResponseMessage] = React.useState('');
        const setMessage = (value: any) => {
            setResponseMessage(value);
        }
        return (
            

    Parent

    Message : {responseMessage}

    ) } export default ParentComponent

    Open App.tsx file in src folder and modify the following code in the same.

    import React from "react";
    import "./App.css";
    import ParentComponent from "./components/ParentComponent";
    const App = () => {
      return ;
    };
    export default App;
    

    Run the application using the following command.

    npm start
    

    Output:

    Childtoparent Output_React

    React: Passing Data between Siblings

    Components present at the same level of the component tree are known as sibling components. Communication between them is a frequent requirement. It is made possible by the parent component as it manages shared state and passes appropriate callbacks to the children components.

    Parent Component- The callback functions and messages are handled by the parent component. It also renders the Child1Component and Child2Component.

    ParentComponent.tsx

    import React, { useState } from "react";
    import Child1Component from "./Child1Component";
    import Child2Component from "./Child2Component";
    
    const styles: { [key: string]: React.CSSProperties } = {
        parentContainer: {
            display: "flex",
            flexDirection: "row",
            justifyContent: "flex-start",
            alignItems: "flex-start",
            color: "white",
            padding: "10px",
        },
    };
    
    const ParentComponent: React.FC = () => {
        const [messageChild1, setMessageChild1] = useState("");
        const [messageChild2, setMessageChild2] = useState("");
    
        const setChild1Message = (value: string) => {
            setMessageChild2(value);
        }
        const setChild2Message = (value: string) => {
            setMessageChild1(value);
        }
    
        return (
            
    ); }; export default ParentComponent;

    Child1Component Component: Once the callback function and message are passed to it from the parent, the child1 component can call the function to send data, trigger an event and display the message that passes from the child2 component

    Child1Component.tsx

    import React, { useState } from 'react'
    
    const styles: { [key: string]: React.CSSProperties } = {
        childContainer: {
            backgroundColor: "#339567",
            color: "white",
            borderRadius: "10px",
            width: "100%",
            margin: "5px",
            textAlign: "center",
        },
        childHeader: {
            fontSize: "3rem",
            marginBottom: "10px",
        },
        childMessage: {
            fontSize: "1.5rem",
        },
        input: {
            padding: "15px",
            width: "50%",
            borderRadius: "8px",
            border: "2px solid white",
            fontSize: "1.2rem",
        },
    };
    interface Child1Props {
        message: string;
        setMessage: (value: string) => void
    }
    
    const Child1Component: React.FC = ({ message, setMessage }) => {
        const [messagealue, setMessageValue] = useState("");
        return (
            

    Child 1

    { setMessageValue(e.target.value); setMessage(e.target.value); }} style={styles.input} placeholder="Type a message..." />

    Message From Child 2 : {message}

    ) } export default Child1Component

    Child2Component Component: The parent passes the callback function and message to the child2, allowing the child2 component to call the function to send data, trigger an event and display the message that passes from the child1 component.

    Child2Component.tsx

    import React, { useState } from 'react'
    const styles: { [key: string]: React.CSSProperties } = {
        childContainer: {
            backgroundColor: "#339567",
            color: "white",
            borderRadius: "10px",
            width: "100%",
            margin: "5px",
            textAlign: "center",
        },
        childHeader: {
            fontSize: "3rem",
            marginBottom: "10px",
        },
        childMessage: {
            fontSize: "1.5rem",
        }, input: {
            padding: "15px",
            width: "50%",
            borderRadius: "8px",
            border: "2px solid white",
            fontSize: "1.2rem",
        },
    };
    interface Child2Props {
        message: string;
        setMessage: (value: string) => void
    }
    
    const Child2Component: React.FC = ({ message, setMessage }) => {
        const [messagealue, setMessageValue] = useState("");
        return (
            

    Child 2

    { setMessageValue(e.target.value); setMessage(e.target.value); }} style={styles.input} placeholder="Type a message..." />

    Message From Child 1 : {message}

    ) } export default Child2Component

    Open App.tsx file in src folder and modify the following code in the same.

    import React from "react";
    import "./App.css";
    import ParentComponent from "./components/ParentComponent";
    const App = () => {
      return ;
    };
    export default App;
    

    Run the application using the following command.

    npm start
    

    Output:

    Siblings Output_React

    React: Context API

    Passing data using props in large and complex React applications can cause very inconvenience. In such instances, ContextAPI provides a more efficient way to pass data between components throughout the component tree. There is no need to manually pass down the props at each level. ContextAPI offers a better way to pass data from a parent component to any deeply nested child component in the component tree.

    Context API in React

    In the code above, the <Employee> component passed the data to the grandchild <EmployeeProfile> component using the React feature of context API. Props were not used anywhere in this communication. 

    3.3 Implementation of ES6 Function

    ECMAScript 6, popularly known as ES6 is a web development feature offering new syntax to write clear and modern programs. It’s continuously updated with the latest features and functionalities. Object Literals string interpolation, Arrow Functions, and Let and Const are some of the features of ES6 that help make JavaScript programming easy for Angular developers. 

    In React, ES6 functions are used to pass object properties. All the props can be automatically inserted with the use of {…props} syntax between open and closed tags.

    let propertiesList = {
    className: "my-favorite-props ",
    id: "myFav",
    content: "Hello my favourite!"
    };
    let SmallDiv = props => 
    ; let mainDiv = < SmallDiv props={propertiesList} />; view raw es6_spread_function.js hosted with by GitHub

    Using the Spread function can be useful when there aren’t any ternary operations or you don’t just have to pass HTML tag attributes and content. Also, it’s not ideal to use the spread function when the functions are used repetitively, in the presence of dynamic properties, when object properties and arrays are required, or when nested tags are needed during rendering. 

    4. Developer Opinion

    Nitin Gupta – As a Project Manager, I value Angular for its numerous built-in functionalities and other comprehensive offerings. Managing large-scale apps has become easy, thanks to its dependency injection and TypeScript-based strong typing. However, if you are looking for faster development cycles, then React can provide you with the required flexibility and the ability to create reusable components. I would choose React for projects requiring rapid development and a lightweight approach. However I would prefer Angular for projects prioritizing maintainability and scalability.

    Dipal Patel – I think both Angular and React are valuable as they cater to different project requirements. When working with a large team, you need Angular’s structured environment. Its two-way data binding simplifies the synchronization between the model and the view. Meanwhile, Virtual DOM from React can enhance the performance of dynamic user interfaces. If you have to choose one, I’d pick Angular to handle enterprise-level apps because of its robust architecture whereas React is my go-to option for small projects where speed is critical.

    Badal Patel – In my experience, choosing between Angular and React often comes down to the specific use case. Angular comes with a modular architecture and a robust CLI which helps boost the productivity of enterprise-grade applications. On the other hand, the component-based architecture from React provides better flexibility and faster rendering times. So, when working on a project that needs frequent updates, I’d choose React for its integration capabilities and huge libraries. On the contrary, Angular is an ideal option for projects that demand robust structure and consistency.

    5. Conclusion

    Both React and Angular are unique technologies, each suited for different use cases. While React outperforms Angular, the latter provides better scalability and can handle unexpected spikes in web traffic. So, each comes with a different set of features and capabilities, making each technology robust in their respective areas. The decision of choosing the suitable tool depends completely on your goals and requirements. 

    Which one of these technologies did you find helpful or would pick for your project? Let us know your reasons in the comments section below.

    FAQs

    Is React better than Angular?

    React provides better backward compatibility, bundle size, and performance than Angular. Moreover, you can save a lot of time and money by reusing components in React’s component-driven architecture. 

    Why choose Angular or React?

    Choose Angular if you want to keep all your data in sync at every level. That’s possible because of its two-way data binding feature. Meanwhile, if you are simply looking for a better cross-platform solution or want something with an easy learning curve then React is the right choice. 

    Is Angular easier than React?

    React uses plain JavaScript and small package sizes. So, it is quite fast and easy to learn. On the contrary, Angular comes with a wide range of built-in functionalities, making the structure a little complicated. Therefore, Angular has a steep learning curve. 

    Does Google use Angular?

    Google has developed this open-source JavaScript framework. So, it’s obvious that Google would use Angular in many of its internal projects such as Google Fiber, and Google AdWords.

    The post React vs Angular: Covering Every Aspects appeared first on TatvaSoft Blog.

    ]]>
    https://www.tatvasoft.com/blog/react-vs-angular/feed/ 0
    React Design Patterns- A Comprehensive Guide https://www.tatvasoft.com/blog/react-design-patterns/ https://www.tatvasoft.com/blog/react-design-patterns/#comments Thu, 09 May 2024 05:00:53 +0000 https://www.tatvasoft.com/blog/?p=12968 Traditional web development was complicated once but with the arrival of React on the scene, the process has been simplified significantly. It also offers great ease of use thanks to the reusable components and its extensive ecosystem.

    The post React Design Patterns- A Comprehensive Guide appeared first on TatvaSoft Blog.

    ]]>

    Key Takeaways

    1. React Design Patterns are used to solve software development problems and simplify the entire process.
    2. Reusability, efficiency, and flexibility are the key benefits of using React design patterns.
    3. Before starting your React app development project, you must know about the popular design patterns like the Container and Presentation pattern, State Reducer pattern, HOCs pattern, and more.
    4. Use these design patterns to make the most of a React library. It allows you to build scalable and easily maintainable applications.

    Traditional web development was complicated once but with the arrival of React on the scene, the process has been simplified significantly. It also offers great ease of use thanks to the reusable components and its extensive ecosystem. 

    React ecosystem provides a large range of tools; some are used to fulfill various development requirements whereas others help resolve different types of issues. React Design Patterns are quick and reliable solutions for your typical development problems. 

    In ReactJS, you can find a large number of design patterns leveraged by Reactjs development companies and each serves a unique purpose in a development project. This article talks about some “need-to-know” design patterns for React developers. 

    But before diving into the topic, it is important to know what are the design patterns in React and how they are useful for app development. 

    1. What is a Reactjs Design Pattern?

    ReactJS design patterns are solutions to common problems that developers face during a typical software development process. They are reusable and help reduce the size of the app code. There is no need to use any duplication process to share the component logic when using React design patterns.

    While working on a software development project, complications are bound to arise. But with reliable solutions from Design patterns, you can easily eliminate those complications and simplify the development process. This also enables you to write easy-to-read code.

    2. Benefits of Using React Design Patterns in App Development 

    If you have any doubt about the effectiveness of React development, it is because you might have yet to take a look at the benefits of React Design Patterns. Their advantages are one of those factors that make React development more effective. 

    2.1 Reusability

    React Design Patterns offer reusable templates that allow you to build reusable components. Therefore, developing applications with these reusable components saves a lot of your time and effort. More importantly, you don’t have to build a React application from the ground up every time you start a new project.

    2.2 Collaborative Development

    React is popular for providing a collaborative environment for software development. It allows different developers to work together on the same project. If not managed properly, this can cause some serious issues. However, the design patterns provide an efficient structure for developers to manage their projects effectively. 

    2.3 Scalability

    Using Design patterns, you can write React programs in an organized manner. This makes app components simpler. So, even if you are working on a large application, maintaining and scaling it becomes easy. And because every component here is independent, you can make changes to one component without affecting another. 

    2.4 Maintainability 

    Design patterns are referred to as the solutions for typical development issues because they provide a systematic approach to programming. It makes coding simple which is not only helpful in developing the codebase but also in maintaining it. This is true even if you are working on large React projects

    React Design Patterns make your code more decoupled and modular which also divides the issues. Modifying and maintaining a code becomes easy when dealing with small chunks of code. It is bound to give satisfactory results because making changes to one section of the code will not affect other parts in a modular architecture. In short, modularity promotes maintainability. 

    2.5 Efficiency 

    Although React has a component-based design, it can provide faster loading time and quick updates, thanks to the Virtual DOM. As an integral aspect of the architecture, Virtual DOM aims to improve the overall efficiency of the application. This also helps offer an enhanced user experience. 

    Moreover, design patterns such as memorization save results of expensive rendering so that you do not have to conduct unnecessary rerenders. Re-renderings take time but if the results are already cached then they can be immediately delivered upon request. This helps improve the app’s performance.

    2.6 Flexibility

    Due to its component-based design, applying modifications to the React apps is convenient. Using this approach allows you to try out various combinations of the components to build unique solutions. Components design patterns also allow you to craft a suitable user interface. Your application needs such flexibility to succeed in the marketplace.

    Unlike other famous web development frameworks, React doesn’t ask you to adhere to specific guidelines or impose any opinions. This offers ample opportunities for developers to express their creativity and try to mix and match various approaches and methodologies in React development. 

    2.7 Consistency

    Adhering to React design patterns provides a consistent look to your application and makes it user-friendly. The uniformity helps offer a better user experience whereas simplicity makes it easy for users to navigate across the app which increases user engagement. Both of these are important factors to boost your revenues.

    3. Top Design Patterns in React that Developers Should Know 

    Design patterns help you resolve issues and challenges arising during development projects. With so many efficient design patterns available in the React ecosystem, it is extremely difficult to include them all in a single post. However, this section sheds some light on the most popular and effective React design patterns.

    3.1 Container and Presentation Patterns

    Container and presentation patterns allow you to reuse the React components easily. Because this design pattern divides components into two different sections based on the logic. The first is container components containing the business logic and the second one is presentation components consisting of presentation logic. 

    Here, the container components are responsible for fetching data and carrying out necessary computations. Meanwhile, presentation components are responsible for rendering the fetched data and computed value on the user interface of the application or website. 

    When using this pattern for React app development, it is recommended that you initially use presentation components only. This will help you analyze if you aren’t passing down too many props that won’t be of any use to the intermediate components and will be further passed to the components below them.

    If you are facing this problem then you have to use container components to separate the props and their data from the components that exist in the middle of the tree structure and place them into the leaf components. 

    The example for container and presentation pattern:

    import React, { useEffect, useState } from "react";
    import UserList from "./UserList";
    
    const UsersContainer = () => {
      const [users, setUsers] = useState([]);
      const [isLoading, setIsLoading] = useState(false);
      const [isError, setIsError] = useState(false);
    
      const getUsers = async () => {
        setIsLoading(true);
        try {
          const response = await fetch(
            "https://jsonplaceholder.typicode.com/users"
          );
          const data = await response.json();
          setIsLoading(false);
          if (!data) return;
          setUsers(data);
        } catch (err) {
          setIsError(true);
        }
      };
    
      useEffect(() => {
        getUsers();
      }, []);
    
      return ;
    };
    
    export default UsersContainer;
    
    
    
    // the component is responsible for displaying the users
    
    import React from "react";
    
    const UserList = ({ isLoading, isError, users }) => {
      if (isLoading && !isError) return 
    Loading...
    ; if (!isLoading && isError) return
    error occurred.unable to load users
    ; if (!users) return null; return ( <>

    Users List

      {users.map((user) => (
    • {user.name} (Mail: {user.email})
    • ))}
    ); }; export default UserList;

    3.2 Component Composition with Hooks

    First introduced in 2019, Hooks gained popularity with the advent of React 16.8. Hooks are the basic functions designed to fulfill the requirements of the components. They are used to provide functional components access to state and React component lifecycle methods. State, effect, and custom hooks are some of the examples of Hooks. 

    Using Hooks with components allows you to make your code modular and more testable. By tying up the Hooks loosely with the components, you can test your code separately. Here is an example of Component composition with Hooks: 

    // creating a custom hook that fetches users
    
    import { useEffect, useState } from "react";
    
    const useFetchUsers = () => {
      const [users, setUsers] = useState([]);
      const [isLoading, setIsLoading] = useState(false);
      const [isError, setIsError] = useState(false);
      const controller = new AbortController();
    
      const getUsers = async () => {
        setIsLoading(true);
        try {
          const response = await fetch(
            "https://jsonplaceholder.typicode.com/users",
            {
              method: "GET",
              credentials: "include",
              mode: "cors",
              headers: {
                "Content-Type": "application/json",
                "Access-Control-Allow-Origin": "*",
              },
              signal: controller.signal,
            }
          );
          const data = await response.json();
          setIsLoading(false);
          if (!data) return;
          setUsers(data);
        } catch (err) {
          setIsError(true);
        }
      };
    
      useEffect(() => {
        getUsers();
        return () => {
          controller.abort();
        };
      }, []);
    
      return [users, isLoading, isError];
    };
    
    export default useFetchUsers;
    

    Now, we have to import this custom hook to use it with the StarWarsCharactersContainer component. 

    Now, we have to import this custom hook to use it with the UsersContainer component.

    import React from "react";
    import UserList from "./UserList";
    import useFetchUsers from "./useFetchUsers";
    
    const UsersContainer = () => {
      const [users, isLoading, isError] = useFetchUsers();
    
      return ;
    };
    
    export default UsersContainer;
    

    3.3 State Reducer Pattern 

    When you are working on a complex React application with different states relying on complex logic then it is recommended to utilize the state reducer design pattern with your custom state logic and the initialstate value. The value here can either be null or some object.

    Instead of changing the state of the component, a reducer function is passed when you use a state reducer design pattern in React. Upon receiving the reducer function, the component will take action with the current state. Based on that action, it returns a new State. 

    The action consists of an object with a type property. The type property either describes the action that needs to be performed or it mentions additional assets that are needed to perform that action. 

    For example, the initial state for an authentication reducer will be an empty object and as a defined action the user has logged in. In this case, the component will return a new state with a logged-in user. 

    The code example for the state reducer pattern for counter is given below:

    import React, { useReducer } from "react";
    
    const initialState = {
      count: 0,
    };
    
    const reducer = (state, action) => {
      switch (action.type) {
        case "increment":
          return { ...state, count: state.count + 1 };
        case "decrement":
          return { ...state, count: state.count - 1 };
        default:
          return state;
      }
    };
    
    const Counter = () => {
      const [state, dispatch] = useReducer(reducer, initialState);
    
      return (
        

    Count: {state.count}

    ); }; export default Counter;

    3.4 Provider Pattern 

    If you want your application to stop sending props or prop drilling to nested components in the tree then you can accomplish it with a provider design pattern. React’s Context API can offer you this pattern.

    import React, { createContext } from "react";
    import "./App.css";
    import Dashboard from "./dashboard";
    
    export const UserContext = createContext("Default user");
    
    const App = () => {
      return (
        
    ); }; export default App; //Dashboard component import React, { useContext } from "react"; import { UserContext } from "../App"; const Dashboard = () => { const userValue = useContext(UserContext); return

    {userValue}

    ; }; export default Dashboard;

    The above provider pattern code shows how you can use context to pass the props directly to the newly created object. Both the provider and the consumer of the state have to be included in the context. In the above code, the dashboard component using UserContext is your consumer and the app component is your provider. 

    Take a look at the visual representation given below for better understanding.

    Provider Pattern

    When you don’t use the provider pattern, you have to pass props from component A to component D through prop drilling where components B and C act as intermediary components. But with the provider pattern, you can directly send the props from A to D. 

    3.5 HOCs (Higher-Order Components) Pattern 

    If you want to reuse the component logic across the entire application then you need a design pattern with advanced features. The higher-order component pattern is the right React pattern for you. It comes with various types of features like data retrieval, logging, and authorization. 

    HOCs are built upon the compositional nature of the React functional components which are JavaScript functions. So, do not mistake them for React APIs. 

    Any higher-order component in your application will have a similar nature to a JavaScript higher-order function. These functions are of pure order with zero side effects. And just as the JavaScript higher-order functions, HOCs also act as a decorator function.

    The structure of a higher-order React component is as given below: 

    const MessageComponent = ({ message }) => {
      return <>{message};
    };
    
    export default MessageComponent;
    
    
    
    const WithUpperCase = (WrappedComponent) => {
      return (props) => {
        const { message } = props;
        const upperCaseMessage = message.toUpperCase();
        return ;
      };
    };
    
    export default WithUpperCase;
    
    
    import React from "react";
    import "./App.css";
    import WithUpperCase from "./withUpperCase";
    import MessageComponent from "./MessageComponent";
    
    const EnhancedComponent = WithUpperCase(MessageComponent);
    
    const App = () => {
      return (
        
    ); }; export default App;

    3.6 Compound Pattern

    The collection of related parts that work together and complement each other is called compound components. A card component with many of its elements is a simple example of such a design pattern.

    Compound Design Patterns

    The functionality provided by the card component is a result of joint efforts from elements like content, images, and actions. 

    import React, { useState } from "react";
    
    const Modal = ({ children }) => {
      const [isOpen, setIsOpen] = useState(false);
    
      const toggleModal = () => {
        setIsOpen(!isOpen);
      };
    
      return (
        
    {React.Children.map(children, (child) => React.cloneElement(child, { isOpen, toggleModal }) )}
    ); }; const ModalTrigger = ({ isOpen, toggleModal, children }) => ( ); const ModalContent = ({ isOpen, toggleModal, children }) => isOpen && (
    × {children}
    ); const App = () => ( Open Modal

    Modal Content

    This is a simple modal content.

    ); export default App;

    Compound components also offer an API that allows you to express connections between various components. 

    3.7 Render Prop Pattern

    React render prop pattern is a method that allows the component to share the function as a prop with other components. It is instrumental in resolving issues related to logic repetition. The component on the receiving end could render content by calling this prop and using the returned value. 

    Because they use child props to pass the functions down to the components, render props are also known as child props. 

    It is difficult for a component in the React app to contain the function or requirement when various components need that specific functionality. Such a problematic situation is called cross-cutting. 

    As discussed, the render prop design pattern passes the function as a prop to the child component. The parent component also shares the same logic and state as the child component. This would help you accomplish Separation of concerns which helps prevent code duplication. 

    Leveraging the render prop method, you can build a component that can manage user components single-handedly. This design pattern will also share its logic with other components of the React application. 

    This will allow the components that require the authentication functionality and its state to access them. This way developers don’t have to rewrite the same code for different components. 

    Render Prop Method Toggle code example:

    import React from "react";
    
    class Toggle extends React.Component {
      constructor(props) {
        super(props);
        this.state = { on: false };
      }
    
      toggle = () => {
        this.setState((state) => ({ on: !state.on }));
      };
    
      render() {
        return this.props.render({
          on: this.state.on,
          toggle: this.toggle,
        });
      }
    }
    
    export default Toggle;
    
    
    
    import React from "react";
    import Toggle from "./toggle";
    
    class App extends React.Component {
      render() {
        return (
          

    Toggle

    (

    The toggle is {on ? "on" : "off"}.

    )} />
    ); } } export default App;

    3.8 React Conditional Design Pattern

    Sometimes while programming a React application, developers have to create elements according to specific conditions. To meet these requirements, developers can leverage the React conditional design pattern. 

    For example, you have to create a login and logout button if you want to add an authentication process to your app. The process of rendering those elements is known as a conditional rendering pattern. The button would be visible to first-time users. 

    The most common conditional statements used in this pattern are the if statement and suppose/else statement. The ‘if statement’ is used when it is required to pass at least one condition. Meanwhile, the developer uses the suppose/else statement when more than one condition has to be passed. 

    You can easily refactor the code given above with the help of the switch/case statement in the following way:

    const MyComponent = ({ isLoggedIn }) => {
      if (isLoggedIn) {
        return ;
      } else {
        return ;
      }
    };
    
    export default MyComponent;
    
    
    
    Example with the help of the switch statement in the following way: 
    
    const MyComponent = ({ status }) => {
      switch (status) {
        case "loading":
          return ;
        case "error":
          return ;
        case "success":
          return ;
        default:
          return null;
      }
    };
    
    export default MyComponent;
    
    

    4. Conclusion

    The React design patterns discussed in this article are some of the most widely used during development projects. You can leverage them to bring out the full potential of the React library. Therefore, it is recommended that you understand them thoroughly and implement them effectively. This would help you build scalable and easily maintainable React applications.

    The post React Design Patterns- A Comprehensive Guide appeared first on TatvaSoft Blog.

    ]]>
    https://www.tatvasoft.com/blog/react-design-patterns/feed/ 1
    How to Use Typescript with React? https://www.tatvasoft.com/blog/typescript-with-react/ https://www.tatvasoft.com/blog/typescript-with-react/#comments Thu, 04 Apr 2024 08:21:11 +0000 https://www.tatvasoft.com/blog/?p=12891 Although TypeScript is a superset of JavaScript, it is a popular programming language in its own right. Developers tend to feel confident programming with TypeScript as it allows you to specify value types in the code. It has a large ecosystem consisting of several libraries and frameworks. Many of them use TypeScript by default but in the case of React, you are given the choice whether to use TypeScript or not.

    The post How to Use Typescript with React? appeared first on TatvaSoft Blog.

    ]]>

    Key Takeaways

    1. Writing TypeScript with React.js is a lot like writing JavaScript with React.js. The main advantage of using TypeScript is that you can provide types for your component’s props which can be used to check correctness and provide inline documentation in editors.
    2. TypeScript enables developers to use modern object-oriented programming features. TypeScript Generics allows the creation of flexible react components that can be used with different data structures.
    3. With TypeScript in React Project, one can perform more compile-time checks for errors and some features become easier to develop.
    4. For TypeScript with React, one can refer to community-driven CheatSheet – React TypeScript covering useful cases and explanations in depth for various modules.

    Although TypeScript is a superset of JavaScript, it is a popular programming language in its own right. Developers tend to feel confident programming with TypeScript as it allows you to specify value types in the code. It has a large ecosystem consisting of several libraries and frameworks. Many of them use TypeScript by default but in the case of React, you are given the choice whether to use TypeScript or not. 

    React is a JS-based library that enables you to create UIs using a declarative, component-based method. Using TypeScript with React has proven to be very effective. You can observe that the offerings of a reputed software development company include React services that focus on crafting elegant user interfaces. In contrast, TypeScript is leveraged to identify code errors, improving the project’s overall quality.

    This tutorial will guide you on how to use TypeScript with React. But first, let’s clear our basics. 

    1. What is Typescript?

    Microsoft created a high-level programming language called TypeScript. It is statically typed. So, it automatically introduces static type checking to your codebase to improve its quality.

    Although React projects mostly use JavaScript, certain features like type annotations, interfaces, and static types that are necessary to detect code errors early on are only available with TypeScript.

    There are many perks such as improved collaboration in large-scale projects, increased productivity, and improved code quality for utilizing types from TypeScript. Because it offers the means to define the data format and structure, the language ensures type safety along with the prevention of runtime errors.

    The conjunction of React and TypeScript enables the developers to build strongly typed React components. It also enforces the type checking in state and props which helps make your code more robust and reliable. 

    TypeScript offerings such as documentation and advanced code navigation features further simplify the work of developers. You can develop robust and easy-to-maintain React applications effortlessly by leveraging the React-TypeScript integration capabilities.

    Further Reading on: JavaScript vs TypeScript

    2. React: With JavaScript or TypeScript? Which One is Better? 

    JavaScript is a popular scripting language. More often it’s the first programming language developers learn for web development. React is a JS-based library that developers prefer to use for building UIs. 

    On the other hand, TypeScript is JavaScript’s superset. So, it offers all the benefits of JavaScript. On top of that, it also provides some powerful tooling and type safety features. Using these languages has its own merits and demerits. So, the choice of whether to use TypeScript or JavaScript with React in your project boils down to your requirements.

    JavaScript features such as high speed, interoperability, rich interfaces, versatility, server load, extended functionality, and less overhead make it a perfect candidate for building fast-changing apps, browser-based apps and websites, and native mobile and desktop applications.

    TypeScript features like rich IDE support, object-oriented programming, type safety, and cross-platform and cross-browser compatibility allow you to build complex and large-scale applications with robust features.

    3. Why Do We Use Typescript with React?

    To avail a multitude of advantages. Some of them are: 

    • Static Type Checking: Static Typing was introduced for React projects in TypeScript. It helps developers identify errors early on. This early detection of potential errors and prevention of runtime errors is possible because of the enforcement of type annotations from the programming language. It makes your code robust and reliable.
    • Improved Code Quality: Typescript language allows the developers to define the return values, function parameters, and strict types for variables. This helps in writing a clean and self-documenting code. The Type system of the language encourages the developers to write more structured and high-quality code. So, your code becomes easy to read and maintain. 
    • Enhanced Developer Productivity: The code editors of TypeScript come with features like real-time error checking, type inference, and auto-completion as a part of advanced tooling support. This helps developers code quickly, find mistakes, implement better coding suggestions, minimize the debugging time, and in the end enhance productivity. 
    • Better Collaboration: It might pique your interest to know that apart from providing coding advantages, TypeScript offers collaboration advantages as well. It provides contract definitions and clear interfaces through type annotations and interfaces. It helps developers understand how different modules and components interact. This improves the overall project understanding. 

    4. Create a React Application with Typescript

    Explore the steps mentioned below to create a React application with Typescript.

    4.1 Prerequisites

    Before we get into action, make sure you are prepared for it. What you will need includes:

    • One Ubuntu 20.04 server. Make sure it is firewall enabled and comes with a non-root user and sudo privileges. Ubuntu 20.04 offers an initial server setup guide. It would help you get started. 
    • Install nodejs and NPM. Use a NodeSource PPA with an Apt. You have to install them on Ubuntu 20.04 to get started. 

    4.2 Create React App

    Create-react-app v2.1 comes with a TypeScript by default. While setting up the new project with CRA, you can use TypeScript as the parameter.

    npx create-react-app hello-tsx --typescript
    

    Tsconfig.json is generated when TypeScript is used for project setup. 

    4.3 Install TypeScript in the React App

    To add a TypeScript version to an existing application, you have to install it with all the necessary types. Execute the following code: 

    npm install --save typescript @types/node @types/react @types/react-dom @types/jest
    

    Next, rename all your files with ts file and tsx file extension. After that, you can start your server which will automatically produce a JSON file named tsconfig.json. Once that happens, you can start writing React in TypeScript. 

    It is important to note that adding TypeScript to existing projects doesn’t mean it will affect the app’s JS code. It would work fine and if you want, you can migrate that code to TypeScript as well. 

    4.4 How to Declare Props?

    The following example depicts how you can use TypeScript to type props in a React component. 

    import React from 'react';
    
    type DisplayUserProps = {
        name: string,
        email: string
    };
    const DisplayUser: React.FC = ({ name, email }) => {
      return (
        
            

    {name}

    {email}

    ) } export default DisplayUser;

    A custom type for DisplayUserProps is defined in the code above. It also includes the name and email. The generic type of React Functional Component is used to define the DisplayUser by taking pre-defined DisplayUserProps as arguments. 

    So, wherever we use the DisplayUser component, we will get the data back as the props. It helps confirm the predefined types such as name and email. The component is called inside App.tsx. 

    const App = () => {
      const name: string = "Cherry Rin";
      const email: string = "cherryrin@xyz.com";
      return (
        
      );
    };
    
    export default App;
    

    After reloading the React app, when you check the UI, it renders the name and email as shown in the example below:

    Cherry Rin

    The TypeScript shows an error when you pass the data that isn’t part of the data structure. 

    
    

    Your console will display the error message as follows:

    error message

    It is how TypeScript ensures that defined types are adhered to when props are passed to the DisplayUser component. This also helps enforce error checking and type safety in the development process. 

    4.5 How to Declare Hooks?

    useRef and useState are the two most common React hooks used in TypeScript. 

    Typing the UseState hook

    Without Types, the useState will look similar to the following command:

    const [number, setNumber] = useState<>(0)
    

    With Types, the useState will look like:

    const [number, setNumber] = useState(0)
    

    And just like that, you can simply declare the state value’s types. The value is determined in <number>. If you or anyone else tries updating the state with another value, the action will be prevented with an error message. 

    error message

    But if you want your state to hold different values then you have to declare:

    const [number, setNumber] = useState(0).
    

    After running this command, you can enter any string or number and it won’t count as an error. 

    The following example depicts how you can use useState in a React component,

    import DisplayUsers from './components/DisplayUsers';
    import { useState } from 'react';
    
    const App = () => {
      const [name, setName] = useState('Cherry Rin');
      const [email, setEmail] = useState('cherryrin@xyz.com');
      return (
        
      );
    };
    export default App;
    

    Typing the UseRef hook

    In React, a DOM component is referenced using the useRef hook. The example given below shows how you can implement it in TypeScript with React.

    const App = () => {
      const nameRef = useRef(null);
    
      const saveName = () => {
        if (nameRef && nameRef.current) {
          console.log("Name: ", nameRef.current.value);
        } 
      };
      return (
        <>
          
          
        
      );
    };
    

    Output:

    Output

    We will be starting with the ref variable as null and declare HTMLInputElement | null as its type. While using the useRef hook with TypeScript, you can assign it to either null or to declared type. 

    The benefit of declaring the useRef hook is that you won’t be reading data or taking actions from the unmatched types as TypeScript will be there to prevent you. You will get the following errors in case for ref, you try to declare a type number. 

    useRef hook

    It helps you avoid making silly errors which saves time that you would have been otherwise spending on debugging. While working on large projects, where multiple people are contributing to the codebase, using TypeScript for React apps provides you with a more ordered and controlled work environment. 

    4.6 How to Declare and Manage States?

    If you have working experience with React or a basic understanding, you would know that adding a simple and stateless component to your React apps isn’t entirely possible. To hold state values in your app component, you have to define state variables.

    The state variable is defined with a useState hook as shown below:

    import React, { useState } from "react";
    function App() {
      const [sampleState, setSampleState] = useState("Ifeoma Imoh");
      return 
    Hello World
    ; } export default App;

    JavaScript

    In this case, the type of state is presumed automatically. By declaring the type your state accepts, you can increase its safety. 

    import React, { useState } from 'react';
    function App() {
      const [sampleState, setSampleState] = useState("Ifeoma Imoh");
      //sampleStateTwo is a string or number
      const [sampleStateTwo, setSampleStateTwo] = useState("");
      //sampleStateThree is an array of string
      const [sampleStateThree, setSampleStateThree] = useState([""]);
      return (
        
    Hello World
    ) } export default App;

    4.7 React Functional Component

    In TypeScript, a functional component or a stateless component is defined with the following commands: 

    type DisplayUserProps = {
        name: string,
        email: string
    };
    
    const DisplayUsers: React.FC = ({ name, email }) => {
      return (
        
            

    {name}

    {email}

    ) } export default Count;

    With React.FC, we will define the expected props object structure. Utilizing props is one of many ways to create the interface. 

    interface DisplayUserProps {
        name: string;
        email: string;
    };
    const DisplayUsers: React.FC = ({ name, email }) => {
      return (
        
            

    {name}

    {email}

    )}

    4.8 How to Display the Users on the UI?

    Now, what shall we do to display the user’s name and email on the screen? The console consists of the name property for all objects. These objects have the user’s name and email. We can use them to display the user’s name and email. 

    Now, you have to replace the content in the App.tsx file with the following:

    import React, { useState } from 'react';
    import { UserList } from '../utils/UserList';
    
    export type UserProps = {
        name: string,
        email: string
    };
    
    const DisplayUsers = () => {
        const [users, setUsers] = useState(UserList);
    
        const renderUsers = () => (
            users.map((user, index) => (
                
                    

    {user.name}

    {user.email}

    )) ); return (

    User List

    {renderUsers()}
    ) } export default DisplayUsers;

    The users array is looped over using the array map method. To destructure the name and email properties of each user object, the object destructuring method is used. Here, the user’s name and email will be displayed on the screen as an unordered list. 

    Now is the time to determine a user as an object that has properties like name and email. For every property, we also have to define a data type. Next, you have to change the useState users array from:

    const [users, setUsers] = useState([]);
    

    to :

    const [users, setUsers] = useState(UserList);
    

    It is to specify users as an array of type users’ objects. It is our declared UI. So, if you check your App.tsx files now, you will see that it no longer has any TypeScript errors.

    specify users as an array of type users’ objects

    As a result, you can see that the screen is displaying a list of 5 random users.

    user list

    4.9 Run App

    Until now, we discussed the basic yet most important concepts for React app development using TypeScript. This section will show how you can leverage them to create a simple to-do app. 

    Create a new React-TypeScript project like we did at the beginning of the article. After that, you have to run the code given below at the app’s root level to start the development server. 

    npm start
    Shell
    

    Now, open the App.tsx file. It consists of a code which you have to replace with the following: 

    import DisplayUser, { DisplayUserProp as UserProps } from './components/DisplayUser';
    import React, { useEffect, useState } from 'react';
    import { UserList } from './utils/UserList';
    
    const App = () => {
      const [users, setUsers] = useState([]);
    
      useEffect(() => {
        if (users.length == 0 && UserList) setUsers(UserList);
      }, [])
    
      const renderUsers = () => (
        users.map((user, index) => (
          
            
          
        ))
      );
    
      return (
        
          

    User List

    {renderUsers()}
    ); }; export default App;

    Here, User data comes from the UserList.ts file which is inside the utils folder. Add the below-mentioned data to the UserList.ts file:

    import { DisplayUserProp as UserProps } from "../components/DisplayUser";
    export const UserList: UserProps[] = [
        {
            name: "Cherry Rin",
            email: "cherryrin@xyz.com"
        },
        {
            name: "Lein Juan",
            email: "leinnj23@xyz.com"
        },
        {
            name: "Rick Gray",
            email: "rpgray@xyz.com"
        },
        {
            name: "Jimm Maroon",
            email: "jimaroonjm@xyz.com"
        },
        {
            name: "Shailey Smith",
            email: "ssmith34@xyz.com"
        },
    ];
    

    To render individual User items in your app, you have to import a DisplayUser component. We will be creating it next. But first, go to your app’s src directory. Open a new components folder. In there, create a DisplayUser file with the tsx extension. Now add the following code to it.

    import React from 'react';
    
    export type DisplayUserProp = {
        name: string,
        email: string
    };
    
    const DisplayUser: React.FC = ({ name, email }) => {
        return (
            

    {name}

    {email}

    ) }; export default DisplayUser;

    After saving all the modifications, test your React app in the browser.

    user list output on browser

    5. Conclusion

    In this article, we have surfed through the fundamentals of using TypeScript with React development. These are the concepts that are widely used in your typical TypeScrip-React projects. We also saw how you can integrate these concepts to build a simple React application. You can imply them similarly in other projects with little modifications to suit your requirements. 

    If you have any queries or input on the matter, feel free to share them with us in the comments section below. We will get back to you ASAP! 

    FAQs

    Can You Use TypeScript with React?

    When it comes to adding type definitions in a JS code, developers prefer to use TypeScript. Only by adding @types/react and @types/react-dom to your React Project, you can get complete JSX and React web support.

    Is TypeScript better for React?

    With static typing, TypeScript helps the React compiler detect code errors early in the development stage. On the other hand, because JavaScript is dynamically typed, the compiler has a hard time detecting code errors.

    The post How to Use Typescript with React? appeared first on TatvaSoft Blog.

    ]]>
    https://www.tatvasoft.com/blog/typescript-with-react/feed/ 1
    Detailed Guide to React App Testing https://www.tatvasoft.com/blog/react-app-testing/ https://www.tatvasoft.com/blog/react-app-testing/#respond Wed, 06 Mar 2024 09:36:08 +0000 https://www.tatvasoft.com/blog/?p=12822 React is a prominent JavaScript library that is used by app development companies to create unique and robust applications. It comes with a declarative style and gives more emphasis on composition. With the help of this technology, every React app development company in the market can transform their client's business by creating modern web applications.

    The post Detailed Guide to React App Testing appeared first on TatvaSoft Blog.

    ]]>

    Key Takeaways

    1. React app testing is crucial for delivering secure, high-performing, and user friendly application.
    2. React Apps are created using different UI components. So it is necessary to test each component separately and also how they behave when integrated.
    3. It is essential to involve Unit Testing, Integration Testing, End-to-End Testing, and SnapShot Testing for a React app as per the requirements.
    4. React Testing Library, Enzyme, Jest, Mocha, Cypress, Playwright, Selenium, JMeter, Jasmin and TestRail are some of the key tools and libraries used for testing React app.

    React is a prominent JavaScript library that is used by app development companies to create unique and robust applications. It comes with a declarative style and gives more emphasis on composition. With the help of this technology, every React app development company in the market can transform their client’s business by creating modern web applications. When businesses grow, the size of the web application along with its complexity will grow for which the development team will have to write tests that can help in avoiding bugs.

    Though testing React apps isn’t an easy task, some frameworks and libraries can make it possible for the development teams. In this article, we will go through such libraries.

    1. Why do We Need to Test the Web App?

    The main reason behind testing applications is to ensure that the apps work properly without any errors. Along with this, in any application, several features might require some attention from the developers as they might cause expensive iterations if not checked frequently. Some of the areas where testing is a must are:

    • Any part of the application that involves getting input from the user or retrieving data from the application’s database and offering that to the user.
    • The features of the application that are connected with call-to-action tasks where user engagement becomes necessary, need to be tested.
    • When any sequential event is being rendered as its elements lead to function, testing is required.

    2. What to Test in React App?

    Developers often get confused about what to test in a React application. The reason behind this confusion is that applications are generally dealing with simple data but sometimes they are quite sophisticated. In any case, developers need to set their priorities for testing the applications. Some of the best things to start the testing process with are:

    • Identifying the widely used React components in the applications and start testing them.
    • Identifying application features that can help in adding more business value and adding them for testing.
    • Executing border case scenarios in high-valued features of React application.
    • Performance and stress testing applications if they are serving a large number of users like Amazon or Netflix.
    • Testing React hooks.

    3. Libraries and Tools Required

    React test libraries and frameworks can be beneficial to offer the best application to the end users. But all these frameworks have their specialty. Here we will have a look at some of these React testing libraries and tools for React application testing.

    3.1 Enzyme

    EnzymeJS

    Enzyme is a React testing library that enables React app developers to traverse and manipulate the runtime of the output. With the help of this tool, the developers can carry out component rendering tasks, find elements, and interact with them. As Enzyme is designed for React, it offers two types of testing methods: mount testing and shallow rendering. This tool is used with Jest.

    Some of the benefits of Enzyme are:

    • Supports DOM rendering.
    • Shallow rendering.
    • React hooks.
    • Simulation during runtime against output.

    3.2 Jest

    JestJS

    Jest is a popular React testing framework or test runner suggested by the React community. The testing team prefers this tool to test applications for large-scale companies. Firms like Airbnb, Uber, and Facebook are already using this tool.

    Some of the benefits of Jest are:

    • Keeps track of large test cases.
    • Easy to configure and use.
    • Snapshot-capturing with Jest.
    • Ability to mock API functions.
    • Conduct parallelization testing method.

    3.3 Mocha

    MochaJS

    It is also a widely used testing framework. Mocha runs on Node.js and testers use it to check applications that are developed using React. It helps developers to conduct testing in a very flexible manner.

    Here are some of the benefits of Mocha:

    • Easy async testing.
    • Easy test suite creation.
    • Highly extensible for mocking libraries.

    3.4 Jasmine

    Jasmine

    Jasmine is a simple JavaScript testing framework for browsers and Node.js. Jasmine comes with a behavior-driven development pattern which means that using this tool can be a perfect choice for configuring an application before using it. Besides this, third-party tools like Enzyme can be used while working with Jasmine for testing React applications. 

    Some of Jasmine’s benefits include:

    • No DOM is required.
    • Asynchronous function testing.
    • Front-end and back-end testing is possible.
    • Inbuilt matcher assertion.
    • Custom equality checker assertion.

    Despite its many benefits, Jasmine isn’t the perfect testing framework for React apps. It doesn’t offer support for testing snapshots. For this, it requires the usage of third-party tools.

    4. How to Test React Applications?

    Here are the steps that can help you test a React application. 

    4.1 Build a Sample React App

    First of all, we will create a minimal application that displays users’ information from an API. This application will be then tested to see how React app testing works. 

    Here, as we only have to focus on the front end of the application, we will use JSONPlaceholder user API. First of all, the developer needs to write the following code in the App.js file:

    import { useEffect, useState } from "react";
    import axios from "axios";
    import { getFormattedUserName } from "./utility";
    import "./App.css";
    
    
    function App() {
      const [users, setUsers] = useState([]);
    
    
      // Fetch the data from the server
      useEffect(() => {
        let isMounted = true;
        const url = "https://jsonplaceholder.typicode.com/users";
        const getUsers = async () => {
          const response = await axios.get(url);
          if (isMounted) {
            setUsers(response.data);
          }
        };
        getUsers();
      }, []);
    
    
      return (
        

    Users:

      {users.map((user) => { return (
    • {user.name} --{" "} ({getFormattedUserName(user.username)})
    • ); })}
    ); } export default App;

    Then, it is time to create a file in the src folder. Name the file utility.js and write the following function in it:

    export function getFormattedUserName(username) {
      return "@" + username;
    }
    

    Now, run the application using this command:

    npm start
    

    Once you run the application, you will see the following output:

    User List- Output

    4.2 Unit Testing

    Now, let’s start with testing the application that we have just developed. Here we will start with unit testing. It is a test for checking individual software units or React components separately. A unit in an application can be anything from a routine, function, module, method, and object. Whatever the test objective the testing team decides to follow specific if the unit testing will offer the expected results or not. A unit test module contains a series of approaches that are provided by React development tools like Jest to specify the structure of the test. 

    To carry out unit testing, developers can use methods like test or describe as the below-given example:

    describe('my function or component', () => {
     test('does the following', () => {
       // add your testing output
     });
    });
    

    In the above example, the test block is the test case and the described block is the test suite. Here, the test suite can hold more than one test case but a test case doesn’t need to be present in a test suite. 

    When any tester is writing inside a test case, he can include assertions that can validate erroneous or successful processes. 

    In the below example, we can see assertions being successful:

    describe('true is truthy and false is falsy', () => {
     test('true is truthy', () => {
       expect(true).toBe(true);
     });
    
     test('false is falsy', () => {
       expect(false).toBe(false);
     });
    });
    

    After this, let us write the first test case that can target the function named

    getFormattedUserName
    

    from the utilitymodule. For this, the developer will have to build a file called utility.test.js. All the test files use this naming pattern: {file}.test.js, there {file} is the module file name that needs to be tested. 

    In this code, the function will take a string as an input and will offer the same string as an output by just adding an @ symbol at its beginning. Here is an example of the same:

    import { getFormattedUserName } from "./utility";
    
    
    describe("utility", () => {
      test("getFormattedUserName adds @ at the start beginning of the username", () => {
        expect(getFormattedUserName("jc")).toBe("@jc");
      });
    });
    

    As seen in the above code, any tester can easily specify the module and test case in the code so that if it fails, they can get an idea about the things that went wrong. As the above code states, the first test is ready, so the next thing to do is run the test cases and wait for the output. For this, the tester needs to run a simple npm command:

    npm run test
    

    After this, one will have to focus on running tests in a single test with the use of the following command:

    npm run test -- -t utility
    

    This can be done when there are other tests created by create-react-app. If by running the above commands, everything goes well, you will be able to see an output like this:

    Unit Test Output

    Successful output.

    Here, in the output, you can observe that one test passed successfully. But if in this case, something goes wrong, then a new test needs to be added to the utils test suite. For this, the below-described code can be useful:

    test('getFormattedUserName function does not add @ when it starts with @is already provided', () => {
        expect(getFormattedUserName('@jc')).toBe('@jc');
      });
    

    This will be a different situation. In this case, if the username already has an @ symbol at the start of the string, then the function will return the output as the username was provided without any other symbol. Here is the output for the same:

    Failed Unit Test

    Failed test output.

    As anticipated, the test failed as the information the system received was the expected value as the output. Here, if the tester can detect the issue, he can also fix it by using the following code:

    export function getFormattedUserName(username) {
      return !username.startsWith("@") ? `@${username}` : username;
    }
    

    The output of this code will be:

    Unit Test Successful

    As you can see, the test is a success.

    4.3 SnapShot Testing

    Now, let us go through another type of testing which is Snapshot testing. This type of test is used by the software development teams when they want to make sure that the UI of the application doesn’t change unexpectedly.

    Snapshot testing is used to render the UI components of the application, take its snapshot, and then compare it with other snapshots that are stored in the file for reference. Here, if the two snapshots match, it means that the test is successful, and if not, then there might have been an unexpected change in the component. To write a test using this method, the tester needs the react-test-renderer library as it allows the rendering of components in React applications. 

    The very first thing a tester needs to do is install the library. For this, the following command can be used:

    npm i react-test-renderer
    

    After this, it’s time to edit the file to include a snapshot test in it.

    import renderer from "react-test-renderer";
    
    // ...
    
    test("check if it renders a correct snapshot", async () => {
      axios.get.mockResolvedValue({ data: fakeUserData });
      const tree = renderer.create().toJSON();
      expect(tree).toMatchSnapshot();
    });
    
    
    // ...
    

    When the tester runs the above code, he will get the following output.

    SnapShot Test Output

    When this test runs, a test runner like Jest creates a snapshot file and adds it to the snapshots folder. Here is how it will look:

    // Jest Snapshot v1, https://goo.gl/fbAQLP
    
    exports[`check if it renders a correct snapshot 1`] = `
    

    Users:

    Loading user details...
    `;

    Now, if one wants to modify the App component, only one single text value needs to be changed. Here, the correct snapshot test will be rendered to fail as there will be a change in the output.

    Renders Correct Snapshot

    To make the test successful, the tester needs to inform a tool like Jest about the intentional changes. This can be easily carried out when Jest is in watch mode. The snapshot as shown below will be taken:

    SnapShot Test Successful

    4.4 End-to-end Testing

    Another popular type of React application testing is end-to-end testing. In this type of testing, the entire system is included. Here all the complexities and dependencies are considered. In general, UI tests are difficult and expensive which is why end-to-tests are carried out rather than unit tests that focus on only the critical parts of the applications. This type of testing comes with various approaches:

    • Usage of platform for automated end-to-end testing.
    • Automated in-house end-to-end testing.
    • Usage of platform for manual end-to-end testing.
    • Manual in-house end-to-end testing.

    4.5 Integration Testing

    Now, we will go through integration testing which is also considered an essential type of react application testing. It is done to ensure that two or more modules can work together with ease.

    For this, the software testing team will have to follow the below-given steps:

    First of all, one needs to install the dependencies with yarn by using the following command:

    yarn add --dev jest @testing-library/react @testing-library/user-event jest-dom nock
    

    Or if you want to install it with npm, use this command line:

    npm i -D jest @testing-library/react @testing-library/user-event jest-dom nock
    

    Now, it’s time to create an integration test suite file named viewGitHubRepositoriesByUsername.spec.js. For this, Jest will be useful to automatically pick it up.

    Now, import dependencies using the code:

    import React from 'react'; // so that we can use JSX syntax
    import {
     render,
     cleanup,
     waitForElement
    } from '@testing-library/react'; // testing helpers
    import userEvent from '@testing-library/user-event' // testing helpers for imitating user events
    import 'jest-dom/extend-expect'; // to extend Jest's expect with DOM assertions
    import nock from 'nock'; // to mock github API
    import {
     FAKE_USERNAME_WITH_REPOS,
     FAKE_USERNAME_WITHOUT_REPOS,
     FAKE_BAD_USERNAME,
     REPOS_LIST
    } from './fixtures/github'; // test data to use in a mock API
    import './helpers/initTestLocalization'; // to configure i18n for tests
    import App from '../App'; // the app that we are going to test
    

    After that, you can set the test suite by following this code

    describe(check GitHub repositories by username', () => {
     beforeAll(() => {
       nock('https://api.github.com')
         .persist()
         .get(`/users/${FAKE_USERNAME_WITH_REPOS}/repos`)
         .query(true)
         .reply(200, REPOS_LIST);
     });
    
     afterEach(cleanup);
    
     describe('if a user of GitHub has public repositories', () => {
       it('Users can view the list of public repositories by entering their GitHub username.', async () => {
         // arrange
         // act
         // assert
       });
     });
    
    
     describe('when a user on GitHub doesn't have any public repos', () => {
       it('The user is informed that the login provided for GitHub does not have any public repositories associated with it.', async () => {
         // arrange
         // act
         // assert
       });
     });
    
     describe('when logged in user does not exist on Github', () => {
       it('user is presented with an error message', async () => {
         // arrange
         // act
         // assert
       });
     });
    });
    

    5. Conclusion

    As seen in this blog, to conduct React app testing, the testing team needs to have a proper understanding of the React testing libraries and tools. After that, they need to find out what React testing is needed for. This can help them choose the right tool from the above-listed ones.

    FAQs

    How is React testing conducted?

    When it comes to React app testing, developers and testers can support the development of high-quality software along with features that can help developers reduce their time in making changes to the development and help testers create a dependable test suite.

    Is React testing library Jest?

    React Testing Library and Jest are two different things. Jest is a tool that helps in writing tests which can be beneficial for components of any application. 

    Where can a React code be tested?

    To test a React code, testers can use any tool like React Testing Library (RTL) and Enzyme. The choice depends on the application type and testing that is required for it.

    The post Detailed Guide to React App Testing appeared first on TatvaSoft Blog.

    ]]>
    https://www.tatvasoft.com/blog/react-app-testing/feed/ 0
    Guide to Deploy React App on Various Cloud Platforms https://www.tatvasoft.com/blog/deploy-react-app/ https://www.tatvasoft.com/blog/deploy-react-app/#respond Wed, 28 Feb 2024 09:32:00 +0000 https://www.tatvasoft.com/blog/?p=12618 For any app development company, the most crucial part of the development process is deployment. This is why the development teams need to understand the different options of deployment that are available in the market and learn how to use them to ensure that the deployment process is carried out smoothly.

    The post Guide to Deploy React App on Various Cloud Platforms appeared first on TatvaSoft Blog.

    ]]>

    Key Takeaways

    1. App deployment is as crucial as app development. Using the right tools helps you pave a smooth path for your product.
    2. AWS Simplify is an inexpensive and simple hosting solution for static web applications.
    3. Vercel is a modern deployment tool offering impressive collaboration capabilities and advanced features like atomic deployment and intelligent edge caching.
    4. Firebase is a Google product offering hosting, authentication, and cloud services to build and scale React apps.
    5. Netlify is an easy-to-use service that allows you to use and deploy multiple project aliases.
    6. Heroku is a popular platform that supports multiple programming languages and offers features such as Git integration, custom domain, and smart containers.
    7. AWS3 helps store and recover data from the internet.
    8. All these hosting and deployment solutions vary in their type and complexity but can still help deploy React applications. Choose one that fits your requirements.

    For any app development company, the most crucial part of the development process is deployment. This is why the development teams need to understand the different options of deployment that are available in the market and learn how to use them to ensure that the deployment process is carried out smoothly. In this blog, we will go through some of the most popular platforms that can be used by React app development companies to quickly and efficiently deploy React applications for their clients. 

    Let’s discuss step by step deployment of React applications using different platforms like AWS Amplify, Vercel, Heroku and more.

    1. AWS Amplify

    One of the most popular platforms to deploy and host modern Reach applications is AWS Amplify Console. It provides custom domain setup, globally available CDNs, password protection, and feature branch deployments. 

    Core Features

    • Authentication
    • DataStore
    • Analytics
    • Functions
    • Geo
    • API
    • Predictions

    Pricing

    • AWS Amplify enables the users to start creating the backend of an application for free and then they can start paying for some specific functionalities if required. Besides this, hosting setup of an application with AWS Amplify for 12 months is free for 1000 build minutes per month and then per minute, it charges $0.01.

    Deploy React App with AWS Amplify

    For React app development companies, sometimes deploying an application becomes a daunting task. But when they use the right tools, the React app developers can carry the process very smoothly. For this, one of the most effective options is Amazon Web Services (AWS). It provides a cost-effective and simple solution for hosting static web app. Here, we will have a look at a step-by-step process that a developer can follow while deploying a React app on Amazon Web Services (AWS).

    Prerequisites:

    Before starting the deployment process, here are a few prerequisites that are required:

    • A React application: The development team must have experience in working with React applications.
    • Amazon Web Services (AWS) Amplify Account: An account for AWS Amplify is required if one doesn’t have it.

    Step 1: Create React App Project

    The very first step of this guide is to create a React application with the use of NPM. NPM is considered an excellent tool used to bridge the gap between the different generations of web development approaches. It enables the developers to ensure efficient and faster app development experience for modern web projects. 

    Here, the React developers need to open the terminal and run the following command to create a new project setup: 

    npx create-react-app react-app-demo
    

    Now, the developer has to upload the application on any version control tool like BitBucket or GitHub. This is done to directly connect the developed app to the host platform.

    Step 2: Select Amplify into AWS Account

    The next step is to choose Amplify in the AWS account and for this, the developer needs to first log in to the AWS Account. To get started with Amplify, click the “AWS Amplify” button as shown in the below image.

    select amplify

    Now, click on the “Get Started” Button to start the process.

    Get Started with Amplify

    Now, under the Amplify Hosting option, click on the “Get Started” button to host the application.

    Host app

    Step 3: Choose Your React App Repo

    The next step is to select the application Repo, for which choose the “GitHub” Button to link your GitHub Account to the AWS Amplify Account.

    select repo

    Now, in the Add repository branch from the drop-down, choose the repository that you want to use to deploy an application on the AWS Amplify Account.

    choose repo

    Step 4: Configure Your React App

    After selecting the repository, one needs to check the configuration of the application and verify the branch code code that will be deployed. As seen in the below image, the app name will be a default Project name, if you want to change it, this is the time. After that, the developer needs to check the code in the “Build and test settings” section and make changes if required.

    choose branch

    After checking everything, the developer can click on the “Next” button.

    Step 5: Deploy a React App

    check build command and name

    Now, you will be diverted to the review page where you can check the repository details along with the app setting details. And if all looks fine, you need to click on the “Save and deploy” button to deploy the app.

    save and deploy

    These steps will deploy the application successfully. If the React developer wants to check the deployed application, he can by clicking on the link promoted in the below image to view the deployed application.

    build and check preview

    Step 6: Preview of Your Deployed React App

    While reviewing the application, the developer can check the URL and can change it if desired by configuring the website domain to an AWS Amplify account. Besides URLs, developers can configure different things like Access Control, Monitoring, Domain, Build Settings, and more.

    preview
    build and check preview in Amplify

    Congratulations on a successful deployment! Your application is now live on AWS Amplify and accessible to the world. Share the link as needed to showcase your application.

    2. Vercel

    Another popular service for the deployment of React applications is Vercel. It is a new approach that developers follow to simplify the deployment process along with team collaboration while creating the React application. This is a service that supports importing source code from GitLab, GitHub, and Bitbucket. With the help of Vercel, developers can get access to starter templates that can help in creating and deploying applications. Besides this, it also offers HTTPS, Serverless functions, and continuous deployment.

    Core Features

    • Infinite Scalability
    • Observability as Priority
    • Intelligent Edge Caching
    • Image Optimization
    • Automatic Failover
    • Multi-AZ Code Execution
    • Atomic Deploys

    Pricing

    • When it comes to hosting Hobby sites on Vercel, there is no charge but for commercial use, the Vercel platform charges from $20 per month per seat.

    Deploy React app with Vercel

    In the world of web development, developers can use different types of tools to deploy a React app. Here we will go through the step-by-step process of deploying a React app on Vercel.

    Prerequisites:

    Before any React app developer starts with this process, here are a few prerequisites for the same:

    • A React application: The development team must have experience in working on a React application that needs to be deployed.
    • Vercel Account: An account in Vercel is required.

    Step 1: Build Your Application

    Step 2: Login into the Vercel Account

    The developer needs to log in to the Vercel Account. For this, they have to click on the “Continue with GitHub” button to log in with the help of the GitHub account. 

    Vercel Login

    Step 3: Choose Your React App Git Repository

    Once the developer logs in, he will be asked to choose the git repository from your GitHub Account. Here one needs to click on the “Import” Button of the repository that the developer needs to deploy the application on.

    Import Repo

    Step 4: Configure Your React App

    Now it’s time to check all configurations of the application. Here the developer needs to check the branch code and make changes in it if required. 

    Then as seen in the below image, the project name will be set as default by the system, if the developer wants to set the react project name in the vercel account he can. 

    Similarly, the default Build Settings commands will be set in the “Build and Output Settings” section, one can change them as per the requirements. 

    Besides this, from the same page, one can set multiple environment variables in the app. For this, there is a section named “Environment Variables”.

    After checking all the configurations and making the required changes, it’s time to deploy the application. For this, the developer needs to click on the “Deploy” button. 

    Set Env

    Step 5: Deploy React App

    After that, you will see a page saying “Congratulations – You just Deployed a New React Project to Vercel”. This means that your application has been deployed. From this page, you can get an instant review of the application by clicking on the “Instant Preview” option.

    deployed React app to Vercel

     Step 6: Preview of Your Deployed React App

    In the application preview page, the developer can check the URL of the deployed application and can make changes to it by configuring the website domain to a Vercel account. To make changes, the developer needs to go to the “setting tab” on Vercel. From here, a developer can also make changes in the security and environmental variables.

    preview
    Change Settings

    Congratulations on a successful deployment! Your React app is now live on Vercel and accessible to the world. Share the link as needed to showcase your application.

    3. Firebase

    Firebase is a widely used platform for developing and scaling React applications. This Google product offers services like application hosting, Cloud Firestore, authentication, cloud functions, and more.

    Core Features

    • Realtime Database
    • Authentication
    • Cloud Messaging
    • Performance Monitoring
    • Test Lab
    • Crashlytics

    Pricing

    • For the Spark Plan, Firebase doesn’t charge anything but this plan offers limited data storage, users, and functions. Another plan is the Blaze Plan for which Firebase charges as per the project type and its requirements.

    Deploy React App with Firebase

    Now, we will have a look at the React development process using Firebase after going through tools like Vercel and AWS Amplify. Here is the step-by-step process of deploying your React app on Firebase.

    Prerequisites:

    Before the developer starts working with Firebase, here are a few prerequisites:

    • A React application: The development team working on Firebase to deploy the React application must have experience in working on the same application. 
    • Firebase Account: An account in Firebase will be required.

    Step 1: Build Your React App

    Step 2: Create a project into Firebase Account

    To login to the Firebase account, the developer needs to click the “Create a project” button.

    create a project in Firebase

    Now, one will have to type the project name and click on the “Continue” Button to start the process.

    set project name

    Now, click on the “Continue” button for the next step.

    step 2

    Select a country from the dropdown, check all checkboxes, and click on the “create project” button.

    step 3

    Step 3: Enable Hosting on Your App

    1. Now, to enable the hosting setup of the application, the developer will have to select the “Hosting” tab from the left sidebar tabs in Firebase Account and click on the “Get Started” button.

    select hosting and started

    Step 4: Install Firebase on Your React App

    After getting started with the hosting process, the developer will have to follow an installation process. 

    1. To install firebase-tool, the developer will have to use the command “npm install -g firebase-tools”.

    install firebase

    3. Now, will have to log in with your Firebase account on your React application with the use “Firebase login” command.

    google login

    4. Initialize firebase on your react application using : “firebase init” command.

    firebase init

    Now, the developer will have to select the “Hosting” option.

    select hosting with optional

    Now, the development team will have to choose the “Use an existing project” option.

    use existing project

    Here, one will have to choose a newly created project from the options.

    select app

    The application is created in the build folder by default, so here the same will be used as the public directory.

    options

    After this, to create react app, the developer will have to run the “npm run build” command.

    run build

    Step 5: Deploy React App

    After this, it’s time to deploy Firebase hosting sites. For this, the developer will have to run the command “firebase deploy”.

    Deploy React app to Firebase

    Step 6: Preview of Your Deployed App

    Once the application is deployed, the developer can preview it and configure the website domain if required from the Firebase account.

    Preview of your Deployed App
    preview links on cmd

    Congratulations on a successful deployment! Your app is now live on Firebase and accessible to the world. Share the link as needed to showcase your application.

    4. Netlify

    The next popular service to deploy a React application in our list is Netlify. This is an easy-to-use service. Developers can import projects from Bitbucket, GitHub, and GitLab. They can create multiple project aliases using this service and deploy it. 

    Core Features

    • Modernize Architecture
    • Faster Time-to-Market
    • Multi-cloud Infrastructure
    • Robust Integrations
    • Effortless Team Management
    • Advanced Security
    • Seamless Migration

    Pricing

    • The basic plan of Netlify is free, then it offers a Pro plan that charges $19 per month for each member, and the enterprise plan is custom-made for the companies as per their requirements and project types. 

    Deploy React App with Netlify

    Here, to overcome the daunting task of React deployment, we will use Netlify, an essential tool for it. This is the step-by-step process of deploying your React app on Netlify.

    Prerequisites:

    Here are a few prerequisites for working with Netlify:

    • A React application: The development team must have experience in working on the application that needs to be deployed. 
    • Netlify Account: An account on Netlify is required.

    Step 1: Build Your ReactJS App

    Step 2: Login into Netlify Account

    To log into the Netlify account, the developer will have to click the “Log in with GitHub” button on the Netlify home page.

    Netlify login

    Step 3: Choose Your React App Repo

    Now, to import the existing project, the developer must click on the “Import from Git” Button to link the GitHub Account to the Netlify Account.

    Import from GIT

    After this, by clicking on the “Deploy with GitHub” option, the developer will be able to import the app repositories from GitHub Account.

    click Deploy with GitHub

    From the list, the developer will have to select the git repository, for the application they want to deploy from your GitHub Account.

    select repo

    Step 4: Configure Your React App

    After importing the application repository, the developer can look at all the application configurations. Here, the developer can check the code of the application and make changes to it if required. 

    Now, as the system will set a default Project name, the developer can even change it. Similarly, the build command setting will be set by default, which can also be changed by going to the “Build Command” section. 

    Besides this, from the same page, the developers can also set multiple environment variables in the React app. This can be done from the “Environment Variables” section.

    Now, to deploy the application after configuring it, the developer needs to click on the “Deploy reactapp-demo” button.

    Add variable

    Step 5: Deploy React App

    Now, the developer will have to go to the “Deploys” section and click on the “Open production deploy” option to get a preview of the deployed React app.

    check deployed preview

     Step 6: Preview of Your Deployed App

    While reviewing the application, the developers can also change the URL of the application from the configuring website domain option in the netlify account.

    Preview
    team overview

    Congratulations on a successful deployment! Your React app is now live on Netlify and accessible to the world. Share the link as needed to showcase your application.

    5. Heroku

    Heroku is used by a large developer community to deploy React applications. This service offers support for various programming languages along with features like a custom domain, a free SSL certificate, and Git integration.

    Core Features

    • Modern Open-Source Languages Support
    • Smart Containers
    • Elastic Runtime
    • Trusted Application Operations
    • Leading Service Ecosystem
    • Vertical and Horizontal Scalability
    • Continuous Integration and Deployment

    Pricing

    • When someone wants to launch hobby projects, Heroku doesn’t charge anything. But for commercial projects, one will have to pay $ 25 per month as it gives advanced features like SSL, memory selection, and analytics.

    Deploy React App with Heroku using Dashboard

    After going through various React deployment platforms, we will now go through the step-by-step process of deploying the React application on Heroku.

    Prerequisites:

    Before starting with Heroku, here are a few prerequisites:

    • A React application: The developer should have worked with the same application that is going through the deployment process. 
    • Heroku Account: The development team must have an account in Heroku.

    Step 1: Build Your React App

    Step 2: Install Heroku on the System

    The developer needs to install Heroku on the system. For this, the command “npm install heroku -g” must be run in the terminal of the system.

    cmd

    If the developer wants to check whether Heroku is already installed in the system or not, he will have to run the “heroku -v” command.

    success install heroku

    Step 3: Login Heroku Account on the system

    No, after getting Heroku in the system, it’s time to log in to the platform. For this, the “heroku login” command can be used. It will also allow the developer to link the GitHub Account to the Heroku Account.

    Heroku login

    After login, you can check whether the login is successful or failed.

    done login

    Step 4: Create React App on Heroku

    Now, the developer can start the app development process by choosing the “Create New App” button on the Heroku platform. 

    create new app

    The developer will have to enter the application name and then click on the “Create app” button.

    create a app

    Now, we need to connect the Git repository to the Heroku account.

    After creating an app, the developer needs to find the option “Connect to GitHub” and choose that option.

    choose gitHub

    After clicking on the “Connect to GitHub” button, you will get a popup where you can write your login credentials for GitHub.

    connect github

    Now choose the git repository of the application that needs to be deployed and click on the “Connect” button to connect that repository.

    connect repo

    After that, select the branch of the code that needs to be deployed and then click on the “Deploy Branch” button to deploy the application.

    select branch and deploy

    Step 5: Preview of Your Deployed React App

    Once you deploy the application, you can see its preview from where you can check the URL of the application and by configuring the domain, you can change it if required. 

    preview

    Congratulations on a successful deployment! Your React app is now live on Heroku and accessible to the world. Share the link as needed to showcase your application.

    6. AWS S3

    AWS S3 (Simple Storage Service) is a platform that offers object storage that is required to create the storage and recover the data & information from the internet. It offers its services via a web services interface. 

    Core Features

    • Lifecycle Management
    • Bucket Policy
    • Data Protection
    • Competitor Services
    • Amazon S3 Console

    Pricing

    • The cost of AWS S3 Standard, a general-purpose storage starts from $0.023 per GB, the price of S3 Intelligent – Tiering, an automatic cost-saving approach for data starts from $0.023 per GB, and other all storage approaches by AWS S3 starts from $0.0125 per GB. 

    Deploy React App to AWS S3

    The last React app deployment tool in our list is Amazon S3 (Simple Storage Service). It is a simple and cost-effective solution for hosting applications and storing data. Here, we will go through the step-by-step process of deploying your React app on AWS S3.

    Prerequisites:

    Before starting with AWS S3, here are some of the prerequisites:

    • A React application: The development team must have experience in working on the application they want to deploy. 
    • AWS Account: An account in AWS is required to access AWS services.

    Step 1: Build Your React App

    In this guide, we’ll create React app using Vite, a powerful build tool designed to bridge the Here, first of all, we will create a React application and for that, the developer will have to run the following command in the terminal.

     npm create vite@latest demo-react-app
    

    Now, to create a production-ready build, one needs to run the below-given command:

     npm run build
    

    This command will help the developer to create an optimized production build in the “dist” directory.

    Step 2: Create an AWS S3 Bucket

    Now, in order to log into the AWS Management Console, and access the S3 service, the developer will have to click on the “Create bucket” button.

    Create an AWS S3 Bucket

    The developer will have to choose a unique name for the bucket and then select the region that is closest to the target audience of the business for improved performance.

    create bucket

    Step 3: Configure S3 Bucket to Host a Static Website

    Enable Static Website Hosting

    Enable Static Website Hosting

    Now, after entering the bucket, the next thing to do is click on the “Properties” tab from the top of the page. After that scroll down to the “Static website hosting” section inside the Properties tab and click on the “Edit” button next to the “Static website hosting” section.

    From here, you will be able to choose Host a static website and use index.html the Index Document, and the Error Document of the project.

    Step 4: Configure Settings and Permissions

    After this, it’s time to configure the permissions and settings of the AWS S3 bucket. This will ensure that the application can be accessed by users only. For this, the developer will have to follow the below-given steps:

     Disable Block Public Access Permissions

    1. Inside the “Permissions” tab of the bucket, find the “Block public access” section as these settings specify if the business owner wants the application to be accessed by the public or not.
    2. Then click on the “Edit” button to access the settings that can help in blocking public access.
    3. Disable all the “Block public access” settings as this will ensure that the app is publicly accessible, if you don’t want that then enable the settings. 

    Besides, when you are inside the “Permissions” tab, find the “Bucket Policy” section. In this section, click on the “Edit” button if you want to create a policy to allow public access to the files of the application. Then copy and paste the below-given commands to generate a policy as per the requirements.

     {
    	"Version": "2012-10-17",
    	"Statement": [
    	 {
    		"Sid": "PublicReadGetObject",
    		"Effect": "Allow",
    		"Principal": "*",
    		"Action": "s3:GetObject",
    		"Resource": "arn:aws:s3:::www.tatvasoft.demo.com/*"
    	 }
    	]
    }
    
    edit bucket policy

    By applying the above-given settings and permissions instructions, the AWS S3 bucket will be ready to serve your React application to the public with some controls. 

    Step 5: Publish React App to S3 then Access it with a Public Link

    Now, the developer will have to publish the application and for that, the following steps will be useful.

    Upload the Contents of Your Build Folder to AWS S3

    First, the developer will have to click on the “Upload” button to begin the process. Then select all the content present in the React application’s “dist” folder but not the folder itself. After that, the developer will have to commence the upload to copy these contents to the AWS S3 bucket.

    Upload the Contents of Your Build Folder to AWS S3

     Use the Public Link to Access Your React App

    Now, after the uploading process is completed, the developer will have to return to the “Properties” tab of the S3 bucket, find the public link in the “Static website hosting” section, and click the link to open the React application in a web browser.

    Static website hosting

    Congratulations on a successful deployment! Your React app is now live on AWS S3 and accessible to the world. Share the link as needed to showcase your application.

    7. Conclusion

    In this blog, we had a look at some amazing services that can be used to host and deploy React applications. All these platforms have their own pros and cons along with different methods and approaches to deploy an application. React app development companies can choose any of these platforms as per the application’s type, complexity, and requirement. 

    FAQs

    Can I deploy React app without server?

    Yes, it is possible to deploy your React App without a server. Just bundle your app during development by allowing the build tool to bundle and minify the JS code, CSS, and all dependencies in separate files. Those JS and CSS files contain necessary app code and are referred to by index.html. Now that you have everything in your app bundled together, you don’t need a server or an NPM module and can just serve your app as a static website. 

    Is Firebase free for deployment?

    Yes, you can use Firebase for free deployment. However, its no-cost tier plan is limited to a certain level of products. To use other high-level products, you have to subscribe to its paid-tier pricing plan. 

    Which is better: AWS or Firebase?

    Both platforms fulfills distinct project requirements. So, there is no competition between AWS and Firebase. If you want to improve app development, minimize the deployment time, and have seamless hosting then Firebase is the right pick for you. But if you are working on a more sophisticated project that demands extensive customized programming and server-level access then you have to go with AWS. 

    Is Netlify better than Vercel?

    Serverless functions are supported in both Nelify and Vercel. But what makes Vercel an excellent choice for serverless applications is that it comes with a serverless architecture. However, integration of serverless workflows with your project is seamless while using Netlify as it also supports AWS Lambda functions.

    The post Guide to Deploy React App on Various Cloud Platforms appeared first on TatvaSoft Blog.

    ]]>
    https://www.tatvasoft.com/blog/deploy-react-app/feed/ 0
    A Complete Guide to React Micro Frontend https://www.tatvasoft.com/blog/react-micro-frontend/ https://www.tatvasoft.com/blog/react-micro-frontend/#respond Tue, 05 Dec 2023 08:15:33 +0000 https://www.tatvasoft.com/blog/?p=12274 It is a difficult and challenging task for developers to manage the entire codebase of the large scale application. Every development team strives to find methods to streamline their work and speed up the delivery of finished products. Fortunately, concepts like micro frontends and microservices are developed to manage the entire project efficiently and have been adopted by application development companies.

    The post A Complete Guide to React Micro Frontend appeared first on TatvaSoft Blog.

    ]]>

    Key Takeaways

    1. When developers from various teams contribute to a single monolith on the top of microservices architecture, it becomes difficult to maintain the large scale application.
    2. To manage the large-scale or complex application, breaking down the frontend into smaller and independently manageable parts is preferable.
    3. React is a fantastic library! One can create robust Micro-Frontends using React and tools like Vite.
    4. Micro Frontend with React provides benefits like higher scalability, rapid deployment, migration, upgradation, automation, etc.

    It is a difficult and challenging task for developers to manage the entire codebase of the large scale application. Every development team strives to find methods to streamline their work and speed up the delivery of finished products. Fortunately, concepts like micro frontends and microservices are developed to manage the entire project efficiently and have been adopted by application development companies

    Micro frontends involve breaking down the frontend side of the large application into small manageable parts. The importance of this design cannot be overstated, as it has the potential to greatly enhance the efficiency and productivity of engineers engaged in frontend code. 

    Through this article, we will look at micro frontend architecture using React and discuss its advantages, disadvantages, and implementation steps. 

    1. What are Micro Frontends?

    The term “micro frontend” refers to a methodology and an application development approach that ensures that the front end of the application is broken down into smaller, more manageable parts which are often developed, tested, and deployed separately from one another. This concept is similar to how the backend is broken down into smaller components in the process of microservices.

    Read More on Microservices Best Practices

    Each micro frontend consists of code for a subset (or “feature”) of the whole website. These components are managed by several groups, each of which focuses on a certain aspect of the business or a particular objective.

    Being a widely used frontend technology, React is a good option for building a micro frontend architecture. Along with the React, we can use vite.js tool for the smooth development process of micro frontend apps. 

    What are Micro frontends

    1.1 Benefits of Micro Frontends

    Here are the key benefits of the Micro Frontend architecture: 

    Key Benefit Description
    Gradual Upgrades
    • It might be a time-consuming and challenging task to add new functionality to a massive, outdated, monolithic front-end application.
    • By dividing the entire application into smaller components, your team can swiftly update and release new features via micro frontends.
    • Using multiple frameworks, many portions of the program may be focused on and new additions can be deployed independently instead of treating the frontend architecture as a single application.
    • By this way, teams can improve overall dependencies management, UX, load time, design, and more.
    Simple Codebases
    • Many times, dealing with a large and complicated code base becomes irritating for the developers.
    • Micro Frontend architecture separates your code into simpler, more manageable parts, and gives you the visibility and clarity you need to write better code.
    Independent Deployment
    • Independent deployment of each component is possible using Micro frontend.
    Tech Agnostic
    • You may keep each app independent from the rest and manage it as a component using micro frontend.
    • Each app can be developed using a different framework, or library as per the requirements.
    Autonomous Teams
    • Dividing a large workforce into subgroups can increase productivity and performance.
    • Each team of developers will be in charge of a certain aspect of the product, enhancing focus and allowing engineers to create a feature as quickly and effectively as possible.

    1.2 Limitations of Micro Frontends

    Here are the key limitations of Micro Frontend architecture: 

    Limitations Description
    Larger Download Sizes
    • Micro Frontends are said to increase download sizes due to redundant dependencies.
    • Larger download rates derive from the fact that each app is made with React or a related library / framework and must download the requirement whenever a user needs to access that particular page.
    Environmental Variations
    • If the development container is unique from the operational container, it might be devastating.
    • If the production container is unique from the development container, the micro frontend will malfunction or act otherwise after release to production.
    • The universal style, which may be a component of the container or other micro frontends, is a particularly delicate aspect of this problem.
    Management Complexity
    • Micro Frontend comes with additional repositories, technologies, development workflows, services, domains, etc. as per the project requirements.
    Compliance Issues
    • It might be challenging to ensure consistency throughout many distinct front-end codebases.
    • To guarantee excellence, continuity, and accountability are kept throughout all teams, effective leadership is required.
    • Compliance difficulties will arise if code review and frequent monitoring are not carried out effectively.

    Please find a Reddit thread below discussing the disadvantages of Micro frontend.

    Comment
    byu/crazyrebel123 from discussion
    inreactjs

    Now, let’s see how Micro Frontend architecture one can build with React and other relevant tools. 

    2. Micro Frontend Architecture Using React

    Micro Frontends are taking the role of monolithic design, which has served as the standard in application development for years. The background of monolithic designs’ popularity is extensive. As a result, many prominent software developers and business figures are enthusiastic supporters. Yet as time goes on, new technologies and concepts emerge that are better than what everyone thinks to are used to.

    The notion of a “micro frontend” in React is not unique; instead, it represents an evolution of previous architectural styles. The foundation of microservice architecture is being extensively influenced by revolutionary innovative trends in social media, cloud technology, and the Internet of Things in order to quickly infiltrate the industry.

    Because of the switch to continuous deployment, the micro frontend with React provides additional benefits to enterprises, such as:

    • High Scalability
    • Rapid Deployment
    • Effective migration and upgrading
    • Technology-independence
    • No issue with the insulation
    • High levels of deployment and automation
    • Reduced development time and cost
    • Fewer Threats to safety and dependability have decreased

    Let’s go through the steps of creating your first micro frontend architecture using React: 

    3. Building Micro Frontend with React and Vite

    Let’s have a look at step by step process of how we can build microfrontend with React and Vite.

    3.1 Set Up the Project Structure

    To begin with, let’s make a folder hierarchy.

    # Create folder named React-vite-federation-demo
    # Folder Hierarchy 
    --/packages
    ----/application
    ----/shared
    

    The following instructions will put you on the fast track:

    mkdir React-vite-federation-demo && cd ./React-vite-federation-demo
    mkdir packages && cd ./packages
    

    The next thing to do is to use the Vite CLI to make two separate directories: 

    1. application, a React app that will use the components, 
    2. shared, which will make them available to other apps.
    #./React-vite-federation-demo/packages
    pnpm create vite application --template React
    pnpm create vite shared --template React
    

    3.2 Set Up pnpm Workspace

    Now that you know you’ll be working with numerous projects in the package’s folder, you can set up your pnpm workspace accordingly.

    A package file will be generated in the package’s root directory for this purpose:

    touch package.json
    

    Write the following code to define various elements in the package.json file. 

    {
      "name": "React-vite-federation-demo", 
      "version": "1.1.0",
      "private": true,   
      "workspaces": [
        "packages/*"
      ],
      "scripts": {
        "build": "pnpm  --parallel --filter \"./**\" build",
        "preview": "pnpm  --parallel --filter \"./**\" preview",
        "stop": "kill-port --port 5000,5001"
      },
      "devDependencies": {
        "kill-port": "^2.0.1",
        "@originjs/vite-plugin-federation": "^1.1.10"
      }
    }
    

    This package.json file is where you specify shared packages and scripts for developing and executing your applications in parallel.

    Then, make a file named “pnpm-workspace.yaml” to include the pnpm workspace configuration:

    touch pnpm-workspace.yaml
    

    Let’s indicate your packages with basic configurations:

    # pnpm-workspace.yaml
    packages:
      - 'packages/*'
    

    Packages for every application are now available for installation:

    pnpm install
    

    3.3 Add Shared Component (Set Up “shared” Package)

    To demonstrate, let’s create a basic button component and include it in our shared package.

    cd ./packages/shared/src && mkdir ./components
    cd ./components && touch Button.jsx
    

    To identify button, add the following code in Button.jsx

    import React from "React";
    import "./Button.css"
    export default ({caption = "Shared Button"}) => ;
    

    Let’s add CSS file for your button:

    touch Button.css
    

    Now, to add styles, write the following code in Button.css

    .shared-button {
        background-color:#ADD8E6;;
        color: white;
        border: 1px solid white;
        padding: 16px 30px;
        font-size: 20px;
        text-align: center;
    }
    

    It’s time to prepare the button to use by vite-plugin-federation, so let’s do that now. This requires modifying vite.config.js file with the following settings:

    import { defineConfig } from 'vite'
    import React from '@vitejs/plugin-React'
    import federation from '@originjs/vite-plugin-federation'
    import dns from 'dns'
    
    dns.setDefaultResultOrder('verbatim')
    
    export default defineConfig({
      plugins: [
        React(),
        federation({
          name: 'shared',
          filename: 'shared.js',
          exposes: {
            './Button': './src/components/Button'
          },
          shared: ['React']
        })
      ],
      preview: {
        host: 'localhost',
        port: 5000,
        strictPort: true,
        headers: {
          "Access-Control-Allow-Origin": "*"
        }
      },
      build: {
        target: 'esnext',
        minify: false,
        cssCodeSplit: false
      }
    })
    

    Set up the plugins, preview, and build sections in this file.

    3.4 Use Shared Component and Set Up “application” Package

    The next step is to incorporate your reusable module into your application’s code. Simply use the shared package’s Button to accomplish this:

    import "./App.css";
    import { useState } from "React";
    import Button from "shared/Button";
    
    function Application() {
      const [count, setCount] = useState(0);
      return (
        

    Application 1

    count is {count}
    ); } export default Application;

    The following must be done in the vite.config.js file:

    import { defineConfig } from 'vite'
    import federation from '@originjs/vite-plugin-federation'
    import dns from 'dns'
    import React from '@vitejs/plugin-React'
    
    dns.setDefaultResultOrder('verbatim')
    
    export default defineConfig({
      plugins: [
        React(),
        federation({
          name: 'application',
          remotes: {
            shared: 'http://localhost:5000/assets/shared.js',
          },
          shared: ['React']
        })
      ],
      preview: {
        host: 'localhost',
        port: 5001,
        strictPort: true,
      },
      build: {
        target: 'esnext',
        minify: false,
        cssCodeSplit: false
      }
    })
    

    In this step, you’ll also configure your plugin to use a community package. The lines match the standard packaging format exactly.

    Application Launch

    The following commands will help you construct and launch your applications:

    pnpm build && pnpm preview
    

    Our shared React application may be accessed at “localhost:5000”:

    Launch Your Application

    At “localhost:5001”, you will see your application with a button from the shared application on “localhost:5000”:

    4. Conclusion

    Micro Frontends are unquestionably cutting-edge design that addresses many issues with monolithic frontend architecture. With a micro frontend, you may benefit from a quick development cycle, increased productivity, periodic upgrades, straightforward codebases, autonomous delivery, autonomous teams, and more.

    Given the high degree of expertise necessary to develop micro frontends with React, we advise working with professionals. Be sure to take into account the automation needs, administrative and regulatory complexities, quality, consistency, and other crucial considerations before choosing the micro frontend application design.

    The post A Complete Guide to React Micro Frontend appeared first on TatvaSoft Blog.

    ]]>
    https://www.tatvasoft.com/blog/react-micro-frontend/feed/ 0
    React Testing Libraries & How to Use Them https://www.tatvasoft.com/blog/react-testing-libraries/ https://www.tatvasoft.com/blog/react-testing-libraries/#respond Wed, 11 Oct 2023 09:20:31 +0000 https://www.tatvasoft.com/blog/?p=12118 Software or application testing is one of the most important parts of software development life cycle. It helps to find out and eliminate potentially destructive bugs and ensure the quality of the final product. When it comes to testing apps, there are various React testing libraries and tools available online. One can test React components similar to any JavaScript code.

    The post React Testing Libraries & How to Use Them appeared first on TatvaSoft Blog.

    ]]>

    Key Takeaways

    1. As per Statista, React is the 2nd most used web framework in the world. There are various tools available for testing react applications. So, best tools and practices must be followed by developers.
    2. Jest, and React Testing Library are the most popular tools recommended by React Community to test react applications.
    3. Other than that, tools like Chai, Mocha, Cypress.io, Jasmine, and Enzyme are widely used for testing react apps.
    4. While selecting testing tools, consider iteration speed, environment required, dependencies, and flow length.

    Software or application testing is one of the most important parts of software development life cycle. It helps to find out and eliminate potentially destructive bugs and ensure the quality of the final product. When it comes to testing apps, there are various React testing libraries and tools preferred by Reactjs development companies. One can test React components similar to any JavaScript code. 

    Now, let’s dive deeper on how you can select best-fit libraries or tools for your project.

    Points to Consider before Selecting React Testing libraries and Tools: 

    1. Iteration Speed
      Many tools offer a quick feedback loop between changes done and displaying the results. But these tools may not model the browser precisely. So, tools like Jest are recommended for good iteration speed.
    2. Requirement of Realistic Environment
      Some tools use a realistic browser environment but they reduce the iteration speed. React testing Libraries like mocha work well in a realistic environment. 
    3. Component Dependencies
      Some react components have dependencies for the modules that may not work best in the testing environment. So, carefully mocking these modules out with proper replacements are required. Tools and libraries like Jest support mocking modules. 
    4. Flow Length
      To test a long flow, frameworks and libraries like Cypress, Playwright, and Puppeteer are used to navigate between multiple assets and routes.

    Now, let’s explore a few of the best options to test React components.

    1. Best React Testing Libraries and Tools

    Here is a list of a few highly recommended testing libraries for React application.

    1.1 Jest

    Jest, a testing framework developed and supported by Facebook, is the industry standard. It has been embraced by companies like Uber and Airbnb for usage in testing React components.

    While looking for a React Testing Framework, the React Community highly suggests Jest. The unit test framework is self-contained, complete with an automated test runner and assertion features.

    Jest

    Github Stars – 42.8K
    Github Forks- 6.5K

    1.1.1 Features of Jest

    • When it comes to JavaScript projects, Jest is meant to run without any further configuration.
    • Individual test procedures are started in parallel to increase throughput.
    • Quick and risk-free.
    • Entire toolkit of Jest is presented at one place. It is well documented and well maintained. 
    • Including untested files, Jest collects code coverage information from entire projects. 

    1.1.2 How to Install Jest?

    Download and install Jest using your preferred package manager:

     
    npm install --save-dev jest
    or
    yarn add --dev jest
    

    1.1.3 First Test Using Jest:

    Now, let’s create a test for a made-up function that supposedly performs a simple arithmetic operation on two values. First, you should make a file called “add.js”

        function add(x, y) {
            return x+y;
        }
        module.exports = add;      
    

    Start by making a new file and naming it add.test.js. Here is where we’ll find the real test:

        const add = require('./add');
    
        test('adds 2 + 2 to equal 4', () => {
        expect(add(1, 2)).toBe(4);
        });
    

    The preceding must be included in the package. json:

        function add(x, y) {
            return x+y;
          }
          module.exports = add;      
    

    This text will be printed by Jest when you run yarn test or npm test:

    PASS ./add.test.js

    ✓ adds 2 + 2 to equal 4 (5ms)

    The First Jest Test case is completed. This check ensured that two values were similar by comparing them using expect and toBe, respectively.

    1.2 React Testing Library

    A sizable developer community stands behind the React-testing-library development. You may simply test components by imitating real-world user actions without relying on the implementation details.

    React Testing Library

    Github Stars – 18.1K
    Github Forks- 1.1K

    To test the React DOM, this package provides a set of tools that work together like an enzyme, mimicking real-world user interactions. You may put your React components through their paces with the help of the React testing package.

    1.2.1 Features of React Testing Library

    • Very light-weight
    • It has inbuilt DOM testing utilities
    • More accessible library

    1.2.2 How to Install React Testing Library?

    Node Package Manager (npm) is already setup with node, thus there’s no need to install anything else to use this component in your project.

        npm install --save-dev @testing-library/react
    

    For yarn users, follow:

        yarn add --dev @testing-library/react
    

    The react and react-dom peerDependencies lists can be found here. To use the React Testing Library v13+, React v18 is required. Upgrade to React 12 if you’re still using an earlier edition in your project.

        npm install --save-dev @testing-library/react@12
    
        yarn add --dev @testing-library/react@12
    

    First Test Case: 

    Create firstApp.js in src directory. 

    firstApp.js

    Write the following code to print the Hello World!

        import React from "react";
    
        export const App = () => 

    Hello World!

    ;

    Now, add the firstApp.test.js file in the src directory. 

        import React from "react";
        import { render } from "@testing-library/react";
        import { firstApp } from "./firstApp";
    
        describe("App Component", function () {
        it("should have Hello World! string", function () {
            let { getByText } = render();
            expect(getByText("Hello world!")).toMatchInlineSnapshot(`
            

    Hello World!

    `); }); });

    1.3 Chai

    One of the most well-known node and browser-based BDD / TDD assertion and expectation React testing libraries is called Chai. It works well with any existing JavaScript testing framework like Mocha, Jest and Enzyme as well.

    Chai

    Github Stars – 8K
    Github Forks- 724

    To specify what should be expected in a test, you may use functionalities like expect, should, and assert. Assertions about functions are another possible use.

    1.3.1 Features of Chai

    • Chai allows software testers to perform various types of assertions.
      • Expect
      • Assert
      • Should
    • The Chai expect and Should styles are used to chain the natural language assertions together. The only difference is chai should style extends “should” with each property. 
    • The Chai assert style offers the developer with a standard assert-dot notation comparable to what is included with node.js.
    • The assert style component additionally offers further tests and browser support.

    1.3.2 How to Install Chai?

    Chai can be downloaded through the NPM. Just enter this into your command prompt to begin the installation process.

        $ npm install --save-dev chai
    

    The chai.js file included in the download may also be used in the browser after it has been installed using the npm package manager. For instance:

        
    

    1.3.3 First Test Using Chai:

    To begin using the library, just import it into your program and select the desired approach (either assert, expect, or should).

        var chai = require('chai');  
        var assert = chai.assert;    // Using Assert style
        var expect = chai.expect;    // Using Expect style
        var should = chai.should();  // Using Should style
    

    app.js

        function app(int a, int b){
            return a*b;
        }    
    

    test.js

        describe(“Multiplication”, () => {
            it(“Multiplies 2 and 3”, () => {
            chai.expect(app(2,3).to.equal(6);
        });
        it(“Multiplies 4 and 2”, () => {
            chai.expect(app(4,2).to.equal(7);
        });
        });    
    

    1.4 Mocha

    Mocha is a popular framework to test react applications. It allows you to use any assertion library, runs tests asynchronously, generates coverage reports, and works in any web browser.

    Mocha

    Github Stars – 22.2K
    Github Forks- 3K

    While putting required codes together for a test, developers use the appropriate React development tools, methodologies and approaches. Mocha is suitable with a broad variety of testing functions and packages. Mocha is a best substitute for Jest because of its simplicity in comparison with Jest in areas like mocking.

    1.4.1 Features of Mocha

    • Capabilities to test synchronous and asynchronous programs using a simple interface.
    • Versatile and precise analysis
    • The capacity to execute tests in a linear manner while monitoring for and reacting to undetected exceptions by tracing them to test cases.
    • Ability to execute functions in a predetermined order and record the results to a terminal window.
    • Software state is automatically cleaned up so that test cases can run separately from one another.

    1.4.2 How to Install Mocha?

    Installing Mocha as a development dependency on your React project is the first step toward utilizing Mocha to test your React apps.

        npm i --save-dev mocha
    

    The following command should be used if Yarn is being used as the package manager:

        yarn add mocha
    

    To include Mocha to your package.json, upgrade the test script first.

        {
            "scripts": {
              "test": "mocha"
            }
          }      
    

    1.4.3 First Test Using Mocha:

        // test/test.js
    
        var modal = require('modal');
        describe('Array', function() {
        describe('#indexOf()', function() {
            it('should return 0 when the value is not present', function() {
            assert.equal([5, 4, 3, 2, 1].indexOf(6), -3);
            });
        });
        });
    

    The aforementioned test looked for the index “6” in the column and reported “-3” if it was not found.

    1.5 Cypress.io

    Cypress is a lightning-fast end-to-end test automation framework by which writing tests can become easier without the need for any extra testing library or tool. It enables testing in production environments, such as actual browsers and command prompts.

    The code may be tested in the actual browser, and browser development tools can be used in tandem with it. The test results for everything may be monitored and managed from the centralized dashboard.

    Cypress.io

    Github Stars – 45K
    Github Forks- 3K

    1.5.1 Features of Cypress

    • Cypress records snapshots over the course of your test runs.
    • Rapid debugging is possible because of the clearly shown errors and stack traces.
    • Cypress will patiently wait for your instructions and statements.
    • Testing that is quick, consistent, and dependable without any hiccups is desirable.

    1.5.2 How to Install Cypress?

    On the command line, type the preceding to initiate a React project:

        npm create vite@latest my-awesome-app -- --template react
    

    Open the folder and type npm install:

        cd my-awesome-app
        npm install
    

    Adding Cypress to the program is the next step.

        npm install cypress -D
    

    Open Cypress:

        npx cypress open
    

    Use Cypress’s Launchpad to get help setting up your work.

    1.5.3 First Test Using Cypress:

    Returning to the Cypress testing app’s “Create your first spec” page, select “Create from component” to get started.

    A prompt will appear with a list of all the element files in the app Cypress will filter out *.config.{js,ts} and *.{cy,spec}.{js,ts,jsx,tsx} from this list. Find the Stepper component by expanding the row for Stepper.jsx.

    src/component/Stepper.cy.jsx is where the following spec file was written:

        src/components/Stepper.cy.jsx
        import React from 'react'
        import Stepper from './Stepper'
        
        describe('', () => {
         it('renders', () => {
           // Check : https://on.cypress.io/mounting-react
           cy.mount()
         })
        })    
    

    The Stepper module is initially brought in. Next, we utilize describe and it to create sections for our tests within method blocks, this allows us to manage the test suite more accurately. Cypress provides these features on a global level, so you won’t need to manually import anything to utilize them.

    The top-level describe block will hold all of the tests in a single file, and each one will be a separate test. The first parameter to the describe feature is the name of the test suite. The second parameter is a feature that will run the tests.

    Here’s the demo video from Cypress – Test Replay Product Demo

    1.6 Jasmine

    Jasmine is an excellent open-source BDD framework and test runner for evaluating a wide variety of JavaScript software. The user interface is put through its paces across a variety of devices and screen sizes, from smartphones to TVs. To ensure their code is bug-free, many Angular CLI programmers also consider Jasmine to be an indispensable tool. Developers typically employ it alongside Babel and Enzyme when testing React applications. The handy util package provides more information about testing your React code.

    Jasmine

    Github Stars – 568
    Github Forks- 429

    1.6.1 Features of Jasmine

    • It’s quick, has little overhead, and doesn’t rely on anything except itself.
    • It provides almost every functionalities and features that one requires to test the code. 
    • You may use it with the browser or Node.
    • It’s compatible with Python and Ruby also.
    • In other words, the DOM is not necessary.
    • It has a simple syntax and an extensive API that is easy to use.
    • The tests and their outcomes can be described in ordinary terms.

    1.6.2 How to Install Jasmine?

    Installing Jasmine as part of the setup is recommended because developers frequently use it in conjunction with Enzyme.

        npm install - - save - dev @babel/core \
                                    @babel/register \
                                    babel-preset-react-app \
                                    cross-env \
                                    jsdom \
                                    jasmine
    
    OR 
    
    yarn add - - dev babel-cli \
                @babel/register \
                babel-preset-react-app \
                cross-env \
                enzyme \
                enzyme-adapter-react-16 \
                jasmine-enzyme \
                jsdom \
                jasmine
    
    

    Follow this command to start Jasmine:

        // For NPM 
        npm jasmine init 
    
        // For Yarn 
        yarn run jasmine init
    

    1.6.3 First Test Using Jasmine

    Jasmine expects all configuration files, such as those for Babel, Enzyme, and JSDOM, to be placed in a spec folder.

        // babel.js
        require('@babel/register');
    
        // for typescript
        require('@babel/register')({
            "extensions": [".ts", ".tsx", ".js", ".jsx"]
        });
    
    
        describe("A suite is a function", function() {
        // For grouping related specs, there is a describe function. 
        // Typically each test file has one describe function at the top level.   
    
        let x;
    
            it("and so is a spec", function() { 
        // Specs are defined by calling the global Jasmine function it.
                x = true;
                expect(x).toBe(true);
            });
        });
    
        describe("The 'toBe' compares with ===", function() {
    
        it("and has a negative case", function() {
                expect(false).not.toBe(true);
            });
    
        it("and has a positive case", function() {
                expect(true).toBe(true);
            });
    
        });
    

    1.7 Enzyme

    When it comes to testing React components, developers may rely on Enzyme, a testing tool created to make the process easier. One of Airbnb’s most popular React testing libraries is called Enzyme. To fully test the React application, developers often pair it with another framework like Jest, Chai, or Mocha. 

    Enzyme

    Github Stars – 20K
    Github Forks- 2.1K

    The sole purpose of the enzyme is to render components, retrieve resources, identify elements, link components, and simulate events. It may make use of assertions written in either Chai or Jest. Testing is simplified by abstracting the rendering of components in React so that you may test their results.

    1.7.1 Features of Enzyme

    • Enzyme’s API aims to be user-friendly and adaptable by modeling itself after jQuery’s API for DOM manipulation and traversal.
    • The Enzyme Application Programming Interface allows for the Inspection of React Elements.
    • It provides shallow rendering.
    • Provides access to enterprise implementations of your component.
    • Provides execution of a complete DOM rendering.
    • There are cases where using react-hooks in shallow rendering is appropriate.

    1.7.2 How to Install Enzyme?

    For installation using npm:

        npm - - save - dev enzyme enzyme-adapter-react-16
    

    7.3 First Test Using Enzyme

    To install Enzyme, write the following command in npm. 

        npm install –save-dev enzyme
    

    Now, create an app.tsx file in the src folder with the following code.

        import React, { Component } from 'react';
        import './App.scss';
    
        class App extends React.Component {
        constructor(props: any) {
            super(props);
            this.state = {        
            };
        }
        render() {
            return (
            
    ) } }; export default App;

    Now, create an app.test.tsx file in the same folder and write the following code.

        import React from 'react'
        import Enzyme, { shallow } from 'enzyme'
        import Adapter from 'enzyme-adapter-react-16'
        import App from './App'
    
        Enzyme.configure({ adapter: new Adapter() })
    
        describe('First Test Case', () => {
        it('it should render button', () => {
            const wrapper = shallow()
            const buttonElement  = wrapper.find('#ClickHere');
            expect(buttonElement).toHaveLength(1);
            expect(buttonElement.text()).toEqual('Click Here');
        })
        })
    

    Then use the “npm test” command to test the code. 

    2. Conclusion

    Because of React’s modular design, TDD (Test Driven Development) is improved. Finding the right technology may facilitate the implementation of this idea and help you to harvest its benefits, from testing specific parts to testing the complete system.

    Combining the proper testing framework (such as Jest, chai, enzyme, etc.) with the necessary assertion/manipulation libraries is the secret to establishing a flexible approach. Using virtual isolation, you can take scalability and TDD to an entirely higher platform by separating components from their tasks (like Bit etc).

    The post React Testing Libraries & How to Use Them appeared first on TatvaSoft Blog.

    ]]>
    https://www.tatvasoft.com/blog/react-testing-libraries/feed/ 0
    MEAN Stack vs MERN Stack: Which Stack to Choose? https://www.tatvasoft.com/blog/mean-stack-vs-mern-stack/ https://www.tatvasoft.com/blog/mean-stack-vs-mern-stack/#comments Tue, 09 May 2023 08:40:23 +0000 https://www.tatvasoft.com/blog/?p=10731 In the recent decade, developers have reached unprecedented heights in terms of creating application stacks. There are two sides to every given online platform: the front end (or user interface) and the back end (or code that runs the site). On the other hand , stack is a collection of frameworks and tools used by web development companies for web applications development. MEAN and MERN are two of them!

    The post MEAN Stack vs MERN Stack: Which Stack to Choose? appeared first on TatvaSoft Blog.

    ]]>
    In the recent decade, developers have reached unprecedented heights in terms of creating application stacks. There are two sides to every given online platform: the front end (or user interface) and the back end (or code that runs the site). On the other hand , stack is a collection of frameworks and tools used by web development companies for web applications development. MEAN and MERN are two of them!

    MEAN stack is a set of JavaScript-based tools used for application development. MERN Stack is a popular replacement for MEAN Stack, in which classic frontend framework Angular is substituted with React.js library. 

    Not sure which one to choose from the MEAN stack vs MERN stack? Well, to choose the best technology stacks for your company, you must be savvy enough to weigh the merits of MEAN stack vs MERN stack. Therefore, this article provides a detailed comparison of the two stacks to assist you in making the best decision for your company.

    1. What is MEAN Stack?

    The MEAN Stack is the most widely useful technology stack for building apps for both web and mobile platforms, especially by full-stack developers. It also uses multiple third-party libraries and tools for large-scale projects.

    MEAN stack leads to faster application development as well as the deployment. Using MEAN stack, one can 

    • Create scalable apps for cloud deployment
    • Simplify deployment process with a built in web server
    • Manage large amount of data

    The MEAN stack consists of four significant elements: MongoDB, Express.js, Angular, and Node.js.

    Technology Key Advantages
    MongoDB One that stores data in a document format rather than a traditional database which is more like an informative set of documents.
    Stores information in a binary JSON format and adds on to what can be done in the cloud.
    Express.js Provides a robust set of features for building API-based web and mobile applications.
    Creates apps with a variety of page types. 
    It’s a server layer built on nodes that offers the stack’s logic.
    Angular It’s a free and open source JavaScript front-end framework for developing user interfaces.
    Supports the Model-View-Controller pattern, which is used to build both web apps and enterprise software.
    Various syntaxes are expressed using the HTML syntax.
    Node.js A server-side runtime environment for executing code, namely JavaScript.
    Conceives and creates software for use in networks and on servers.
    Develops web-based I/O frameworks for software.

    1.1 Advantages and Disadvantages of MEAN Stack

    Advantages of MEAN Stack:

    1. JavaScript Everywhere: The MEAN tech stack uses JavaScript for everything like database, frontend, and backend. It makes the development process smooth and consistent. 
    2. Open Source: All frameworks in this tech stack are open source. It helps avoid any kind of vendor lock-in. 
    3. Speed: MEAN is fast because both MongoDB and NodeJS offer high performance.
    4. Flexibility: Because both MongoDB and ExpressJS are flexible, MEAN becomes easily integrable or adaptable to any use case. 
    5. Full Stack for Web: This stack provides everything you need to build a robust, and interactive web application.

    Disadvantages of MEAN Stack:

    1. Learning curve: Learning all four frameworks of the stack is a difficult undertaking, especially for beginners. 
    2. Performance: Although NodeJS is popular for speed and performance, it doesn’t work well when you need a lot of CPU-intensive processing. 
    3. Community support: Although the number of supporters is growing for the MEAN stack, it isn’t quite there yet in comparison to other web development stacks like Ruby on Rails or LAMP. 
    4. Security: The components of the stack offer some default security features but it can do well with additional measures such as authentication and authorization to ensure the app’s security.

    2. What is MERN Stack?

    A popular alternative to the MEAN Stack is the MERN Technology Stack, which swaps out the cumbersome and time-consuming Angular in favor of the more straightforward and simple React.js in any software development.

    MongoDB, Express.js, React.js, and Node.js form the “MERN” acronym, which describes this combination of technologies. Let’s examine the functions of each of these parts in further detail.

    Technology Key Advantages
    MongoDB Document-oriented, highly scalable, NoSQL database that works on several platforms.
    MongoDB has the JavaScript interface Mongo Shell for performing operations.
    Express.js Operates as a layer atop Node.js that provides assistance to the backend framework.
    The modular framework helps developers save time by facilitating code reuse and supporting middleware.
    React.js A front-end Library for developing Interactive UIs.
    Ideal for use in single-page and mobile apps.
    It’s quick to process data that’s constantly changing.
    Node.js Using its frameworks, programmers can build the backend for single-page web apps.
    It works with Node Pack Manager (npm), which provides access to hundreds of open-source and commercial Node modules.

    2.1 Advantages and Disadvantages of MERN Stack

    Advantages of MERN Stack:

    1. Single Language: The MERN stack is built singularly on JavaScript. So developers can easily switch back and forth between frontend and backend development. 
    2. High Performance: The MERN stack offers high performance and scalability thanks to the server-side programming from NodeJS. 
    3. Large Community: The MERN stack has the support of a large and active community that offers access to the massive treasury of tools, tutorials, resources, and support services. 
    4. Modular Architecture: The modular architecture of the MERN stack enables the developers to reuse the code and components which significantly cut down the costs as well as development time.

    Disadvantages of MERN Stack:

    1. Steep Learning Curve: Learning the MERN stack is challenging especially if you do not have any experience or knowledge of the involved technologies. 
    2. Security Concerns: Security is a primary concern with MERN. To protect your web app against potential cyberattacks, you need to take appropriate security measures.

    3. MEAN Stack vs MERN Stack

    Let’s first understand the architecture of both the stacks. 

    3.1 MEAN Stack Architecture

    The MEAN architecture was created to drastically simplify the process of creating a JavaScript-based web application capable of working with JSON.

    MEAN Stack Architecture

    Angular.js as a Front-end Framework

    Angular, which calls itself a “JavaScript MVW Framework”, is classically used in the MEAN stack.

    Compared to manually coding a website in static HTML and JavaScript, Angular makes it much easier to construct dynamic, interactive online experiences by extending your HTML tags with information (or jQuery).

    Form authentication, localization, and two-way communication with your back-end service are key features of Angular. Here is the Quora answer from Google’s UX Engineer on usefulness of Angular in the MEAN Stack.

    Quora

    3.2 MERN Stack Architecture

    With the MERN architecture, you can quickly and simply build a full front-to-back-to-database stack just in JavaScript and JSON.

    MERN Stack Architecture

    React.js as a Front-end Library

    React.js, the expressive JavaScript library for developing interactive HTML client-side apps, is the crown jewel of the MERN stack. Using React, you can construct sophisticated user interfaces with elementary building blocks, bind them to server-side data, and output the result as HTML.

    When it comes to domain-specific, data-driven UI, React shines. It also includes all the features you’d want from a professional web framework, such as excellent coverage for forms, error detection, events, listings, and many more.

    3.3 MEAN and MERN Stack Common Architectural Components

    Express.js and Node.js Server Tier

    Express.js is a web framework that you can deploy on a Node.js server. It describes itself as a “rapid, unbiased, simple web framework for Node.js,” which it is.

    Express has strong techniques for handling HTTP requests, responses, and URL routing, which is the activity of linking an arriving URL with a server operation. Your Angular.js app’s front end may communicate with the backend Express.js services using XML HTTP requests (XHRs), GETs, and POSTs.

    Those methods then access and modify the MongoDB database utilizing the Node.js drivers through callbacks or using promises.

    MongoDB Database Tier

    You’ll need a database that’s as straightforward to deal with as Angular or React, Express, and Node if the app keeps personal profiles, data, remarks, transfers, events, and so on.

    Here is when MongoDB enters through: JSON documents may be sent to the Express.js servers after being produced by the Angular.js or React front end also validated and (if found to be correct) saved in MongoDB.

    4.1 Learning Curve

    MongoDB, ExpressJS, and NodeJS have extensive documentation which significantly improves the learning curve. The notable difference lies between the learning curves of Angular and React. Angular is a framework that consists of typescript and templates. But its learning curve is steeper in comparison to React. Meanwhile, React is easy to learn and offers better documentation. 

    4.2 Popularity

    Both technology stacks are very popular among developers. However, due to its ease of use, high performance, and large community support, React garners a little more popularity than Angular. 

    4.3 Productivity

    Building robust web apps with the MEAN stack is easy as it provides more unique features and a pre-built set of modules. MERN stack on the other hand demands a little effort in configuration and setup but offers great customization and flexibility.

    4.4 Community Support

    Both MEAN and MERN stacks enjoy the support of strong and active developer communities. But the community of the React framework is a little diverse which means it has more resources at its disposal for problem-solving.

    4.5 Project Requirements

    You have to thoroughly analyze the project requirements such as integration, security, performance, scalability, and more. It would help you determine which tech stack is suitable for your project. The MEAN is comprehensive yet a robust tech stack. MERN seems more like a flexible and lightweight tech stack. 

    4.6 Security

    The differentiators between both stacks are Angular and ReactJS frameworks. So we will talk about security in terms of these frameworks. 

    Angular offers Input validation, data sanitization, and some other security features by default against CSRF and XSS attacks. It also provides out-of-the-box peerless security mechanisms which makes it easy for developers to build secure apps using the MEAN stack. 

    In the MERN stack, ReactJS doesn’t come with any security features. So they have to leverage the modules and libraries from the ecosystems of ExpressJS and NodeJS to ensure secure app development. 

    4.7 Companies who use MEAN and MERN

    Top companies like Paypal, Accenture, Intel, and The Weather Channel use the MEAN stack whereas Airbnb, Netflix, Uber, and Facebook use the MERN stack. 

    5. Tabular Comparison: MEAN Stack vs MERN Stack

    MEAN StackMERN Stack
    Front-end Framework / LibraryMEAN utilizes Angular as its frontend framework.MERN utilizes ReactJS library for the frontend development.
    Supported ByMEAN has the support of Google Inc.MERN has Facebook’s support.
    Learning CurveIt has a steeper learning curve.It’s a lot less complicated to pick up.
    Framework UpdationFrom release 1 to edition 2, Angular saw significant changes.When it comes to consistent UI rendering, React.js outperforms Angular.js.
    Key ObjectiveCode abstraction is what MEAN takes care of, and it also handles file management.A faster rate of code development is achieved via MERN.
    When to Prefer?At the operational level, MEAN Stack is the preferred architecture.When time and effort are of the essence, smaller applications are better served by MERN.
    Usage of External LibrariesIt already has functionality that may be put to use to facilitate the usage of a wide variety of external libraries.There aren’t any built-in libraries in React.js that can handle such requests.
    Programmer EfficiencyThe software allows for more efficient programming.Developer efficiency is decreased with React.
    Modification in UIWhen a user makes a modification to the user interface, the corresponding change in the model state is reflected immediately.No information is sent back and forth between the UI and the model, just the other way around.
    Project SizeDevelopment of large sized projects is preferable using MEAN stack.Development of small sized projects is more preferable using MERN stack.

    6. When to Use MEAN Stack? 

    Display tier (Angular.js or Angular), application tier (Express.js and Node.js), and database tier (MongoDB) are the three components that makeup MEAN’s take on the classic three-tier JavaScript stack structure.

    You should give MEAN significant consideration if you’re developing a JavaScript project, especially in Node.js and angular.

    While the MongoDB Query Language (MQL) is expressed in JSON, the command line interface (CLI) is a JavaScript translator, and the data itself is stored in a JSON-like format (BSON, a binary JSON extension). MongoDB is a JavaScript/JSON data repository that also supports robust native Node.js drivers and is built for horizontal scalability, and offers sophisticated capabilities like indexing and searching deep into JSON documents. Using MongoDB Atlas, MongoDB developers develop the cloud-native database as a service, cloud-based application development has never been simpler.

    MEAN is the best stack for developing Node.js apps, whether you’re making a microservice, a basic web app, or an API with maximum bandwidth.

    7. When to Use MERN Stack?

    Since the MERN Stack uses JavaScript, there is no requirement for the programmer to transition between different contexts. When it comes to abstracting the UI layer, React js library in the MERN Stack, excels. To facilitate the straightforward development fostered by the MVC architecture design, MERN provides a library with an easily accessible interface that allows rapid code execution. Big, reactive JSON data that can move easily between the front and back ends of an application is ideal since it can be easily managed and updated.

    MERN is a general-purpose web stack, so you may use it to create anything you choose; however, it shines in scenarios that need significant use of JSON, are native to the cloud, and have interactive web interfaces.

    Project management, data aggregation, to-do applications and calendars, engaging forums and social goods, and anything else you can think of are all examples.

    8. Conclusion

    Due to their tight relationship, MEAN and MERN stacks make it difficult to pick only one for web development. The foundations and competencies of both technologies are dependable. Yet, MEAN is more useful for large-scale apps, whereas MERN for faster development of smaller apps due to structural differences. Consequently, it is important to pick from the MEAN stack vs MERN stack based on the requirements of your application.

    FAQs

    Which is better MERN stack or MEAN stack?

    The use of the MERN stack is ideal for developing real-time applications because MERN supports Socket.io. Meanwhile, if you are developing a traditional web app then MEAN stack is the right fit as it offers the necessary Angular expertise. 

    Is MERN stack in demand?

    Because of its open-source nature, scalability, and versatility, the demand for the MERN stack is very high in the web development arena. 

    What is the difference between MEAN stack and full-stack?

    The difference between Full-stack and MEAN stack lies in its scope of work. The Full-stack refers to working on both frontend and backend along with other APIs. Whereas MEAN stack only involves a definite set of frameworks like MongoDB, ExpressJS, AngularJS, and NodeJS. 

    Is MEAN stack the future?

    The MEAN stack is considered the future of web development as it is a combination of robust technologies that leverage JavaScript to create interactive web applications.

    The post MEAN Stack vs MERN Stack: Which Stack to Choose? appeared first on TatvaSoft Blog.

    ]]>
    https://www.tatvasoft.com/blog/mean-stack-vs-mern-stack/feed/ 1
    Angular Vs React Vs Vue: Which One To Choose https://www.tatvasoft.com/blog/angular-vs-react-vs-vue/ https://www.tatvasoft.com/blog/angular-vs-react-vs-vue/#comments Wed, 11 Jan 2023 11:07:47 +0000 https://www.tatvasoft.com/blog/?p=9436 When it comes to creating web apps, the biggest concern front-end developers have is which frontend framework to choose as there are many JavaScript frameworks available in the market. The top three front-end frameworks or libraries that every expert suggests are Angular, React, and Vue.

    The post Angular Vs React Vs Vue: Which One To Choose appeared first on TatvaSoft Blog.

    ]]>
    When it comes to creating web apps, the biggest concern front-end developers have is which frontend framework to choose as there are many JavaScript frameworks available in the market. The top three front-end frameworks or libraries that every expert suggests are Angular, React, and Vue. There is a huge competition between Angular vs React vs Vue. Angular is a fully-fledged framework and the best practices of Angular enable developers to create robust applications. React is not a framework, it is a UI library that helps in creating unique user interfaces, and Vue is a progressive JavaScript framework used for developing web apps. To make the right choice among these three, the developers have to go through the comparison among Angular, React, and Vue’s key points and understand their differences. In this blog, we will first understand two JavaScript frameworks and one library and then go through their differences.

    1. History of Angular, React, and Vue

    Angular is one of the best frameworks developed by Google. It was released in 2010 and this makes it the oldest framework in comparison with Vue and React. It is a popular TypeScript-based framework with an MIT license and having an MIT license means that these products offer limited restrictions on reuse. In the year 2016, a shift happened and the new version of Angular, version 2 was released. This version dropped JS from the original name – AngularJS. Angular 2+ is called Angular and version 1 is called AngularJS.

    React is a library which is developed by Facebook. It was developed in the year 2013 and since then it has been used to develop complex applications. React uses an MIT license. Facebook itself uses React and React Native in its products like WhatsApp, Facebook, and Instagram.

    The Vue framework is one of the most popular and younger frameworks in this group. It was developed by Evan You, an ex-Google employee in 2014. This framework holds an MIT license. It has been through a substantial shift in the last few years and the latest versions of Vue are always announced on the official Vue website. It has its own GitHub repo and functions with the use of TypeScript.

    Further Reading VueJS Guide for Beginners

    AngularReactVue
    Official Siteangular.ioreactjs.orgvuejs.org
    Initial Release201020132014
    Current Version13.x17.x3.x
    LicenseMITMITMIT
    Used ByGoogle, WixFacebook, UberAlibaba, GitLab

    When it comes to having a legit license to make sure that these open-source JavaScript frameworks are good for web development, all three of them use the MIT license. Having an MIT license means that these products offer limited restrictions on reuse.

    2. What is Angular? 

    Launched in 2010, Angular is a cross-platform JavaScript-based framework developed by Google. Written in TypeScript, Angular uses a regular DOM to build applications ranging from SPAs to enterprise applications. 

    Maybe that is the reason why this framework has a large community consisting of over 1.7 million developers and contributors. In addition to development and testing, Angular also provides a variety of functionalities for state management, routing, PWA, and so on.

    2.1 Angular Features

    • Two-Way Data Binding: Modifications made in the Model are reflected in the View in real time and vice versa. 
    • MVC Architecture: The Model-View-Controller architecture lets you handle and organize your program effectively. 
    • Dependency Injection: It helps promote modular programs and handle dependencies. 
    • CLI: This feature is called the Command Line Interface. It helps you manage and scaffold Angular projects. 
    • Document Object Model: DOM makes the XML or HTML page a tree-like structure where every single node indicates a particular section of content. Instead of updating the modified HTML tags, Angular updates the entire tree-like structure. 
    • TypeScript: Developers can use TypeScript to write understandable JS code.

    2.2 Angular Advantages 

    • Large Ecosystem: Angular comes with a large array of tools and libraries for reactive programming, project scaffolding, and testing. It is a unified framework that offers enhanced developer experience.
    • Increased development efficiency: the dependency injection system allows developers to write modular and testable code. It also helps streamline the services and components management process which increases the development efficiency. 
    • Reduced errors: Two-way data binding ensures that the View and Model are in sync. This not only provides real-time interactivity but also reduces the possibility of errors as the modifications are made automatically to the user interface. 
    • Reusability: Angular has adopted a modular approach to software development. This means that the app is built by arranging the small chunks of code together. Each section of code is developed and deployed independently. This makes it easier to maintain and scale teh application. These pieces of code are reusable.

    2.3 Angular Disadvantages 

    • Learning Curve: The framework consists of some complex topics that are fundamental for development. The syntax is also complex in comparison to other frameworks. So, Angular has a steep learning curve. 
    • Fewer SEO features: Indexing Angular applications in search engines is difficult because, Angular has very limited options in terms of SEO. 
    • Migration: Migrating your existing app from a different technology framework to Angular is challenging. Even updating from an older version to the latest version is difficult when using Angular.

    3. What is ReactJS?

    Facebook developed a comprehensive UI library based on JavaScript called React. It is open-source and enables you to build reusable UI components. Putting these reusable components together will allow you to create a full-fledged user interface for your application.

    The process of creating a dynamic UI is complex but it can also be easily streamlined using this frontend framework. 

    3.1 ReactJS Features 

    • Component-Based: React comes with a component-based architecture. Components in React are reusable and independent. 
    • Virtual DOM: All the changes are first made in the Virtual DOM. Only the necessary changes are updated in the actual DOM.
    • JSX: It is a syntax extension that enables the developers to use both the JavaScript code and HTML code together for app development. 
    • One-Way Data Binding: As the name suggests, the data flow in Angular is unidirectional. It’s from top to bottom or from parent components to child components. 
    • React Native: Allows you to create native mobile apps with the React framework.

    3.2 ReactJS Advantages 

    • Easy to learn: With simple syntax, React is easy to learn if you are familiar with HTML. You don’t even need to have a deep understanding of TypeScript language. 
    • Open-source: React is an open-source framework that helps garner support from a large and active community.
    • Flexibility: Angular provides high-level flexibility which allows you to build responsive applications. 
    • Easy migration: Facebook has included “codemods” in its Angular offerings which enables you to automate most of the migration process that takes place between different versions. 

    3.3 ReactJS Disadvantages 

    • Frequent updates: ReactJS is updated frequently which doesn’t leave much time for developers to document an organized approach. Until they do, their approach or functionality itself becomes outdated. 
    • Unopinionated: React doesn’t offer specific procedures or guiding principles for developers to follow. This gives them too many options which ends up confusing them and delaying the projects.

    4. What is VueJS? 

    Deriving from his experience with Angular at Google, Evan You launched a new framework called Vue in 2014. It retains the best elements of Angular and is still considerably lightweight. 

    This open-source JavaScript-based framework offers pre-built directives and user-defined directives. In addition to that, it also allows you to extend those directives. Powered with an MVVM architecture design pattern, Vue helps you create high-quality SPAs and engaging UIs for web apps. 

    4.1 VueJS Features 

    • Vue Router and Vuex: Vue Router is the official routing library whereas VueX is a state management library from Vue.
    • Virtual DOM: As a digital representation of DOM, it helps create and modify the objects mirroring the original DOM. The final updates of the virtual DOM are then implemented in the actual DOM. 
    • Data Binding: It allows smooth sync between the data in the Vue instance and presentation in the HTML markup. This helps improve VueJS app’s responsiveness
    • Components: Components in VueJS are independent elements that come with their own view and logic. Following a modular approach, VueJs enables the developers to create reusable code. 
    • Event Management: This feature allows you to effectively manage system events as well as user interactions in your Vue apps. 

    4.2 VueJS Advantages 

    • Lightweight: The Vue zip file is 18 kb only. Saving less memory allows the framework to get installed quickly and work faster. It is also beneficial in enhancing the user experience and SEO. 
    • Well-documented: Vue documentation is very well organized and can help you build a full-scale application even if you are only familiar with the basics of JavaScript and HTML. 
    • Adaptability: VueJS shares many similarities with other frameworks such as React and Angular in terms of design and architecture. So, you can easily switch frameworks or migrate your app to another framework. 
    • Flexibility: Developers can use Vue either as a full-fledged framework to build large-scale apps or use it as a simple library for specific features. The choice is up to you. 

    4.3 VueJS Disadvantages 

    • Learning Curve: Although popular for its simplicity, Vue may be difficult to learn when it comes to building large-scale applications. With the increased project complexities, the code grows to be messy. 
    • Limited Ecosystem: Vue lacks the necessary resources. Hence, it has a small ecosystem compared to frameworks like Angular and React. Using Vue, you get very limited support, third-party libraries, and so on.

    5. Detailed Comparison of three JavaScript Frameworks: Angular vs React vs Vue

    5.1 Popularity 

    Angular is created by Google which automatically makes it popular amongst developers. It is often used to develop large-scale applications by experienced developers. As per the data by BuiltWith, Angular powers more than 97k websites. It has 68k stars on Angular GitHub.

    React is among the most popular JavaScript libraries with around 160k stars on React GitHub. According to BuiltWith’s statistics, it is a product by Facebook and powers more than 11 million websites.

    Vue holds 176k stars on Vue GitHub and has solid independence compared to Angular and React. It has an open-source community and is used by more than 2 million websites as per BuiltWith.

    Besides this, amongst all the popular web app development frameworks, ReactJs stands 2nd with 35.9%, Angular at 3rd position with 25.1%, and VueJs with 7th position with 17.3% of usage by developers in the market.

    Popularity 
    AngularReactVue
    Stars83.9k7.9k32.7k
    Forks22.2k6.4k5.9k
    Watchers3.1k199746
    Contributors1614+1622+332+

    5.2 Rendering: Angular vs Vue vs React

    There are two types of rendering: client side and server side. Every framework has a mechanism in place to pursue rendering. Let’s see how each of our contenders handles rendering. 

    Rendering in Angular 

    By default, all the web pages in Angular are rendered in the DOM, and apps are executed in the browser as a part of client-side rendering. This paves the way for various problems like lack of visibility for search engine crawlers and poor app performance. 

    But fret not, Angular also allows you to choose server-side rendering using Angular Universal. With this solution, you can easily render apps on the server side and then return static HTML content to the browser on the client side. SSR improves page loading time, user experience, social media previews, and SEO performance. 

    Hence, the overall performance of your Angular application can be enhanced using server-side rendering.

    Rendering in React 

    React delivers a basic HTML file to the client. This file gives a reference to the JavaScript bundle that contains ReactJS code. The client can render the web page only when it receives this bundle containing the necessary logic and components. 

    However, React faces the same problems as Angular in terms of client-side rendering. To avoid them, you can opt for server-side rendering in React by using frameworks such as Gatsby and NextJS. 

    Additionally, utilizing React Server Components, you can directly write server-side code such as data queries in React components. Although it is not technically SSR, using this method reduces the quantity of data required to transfer between the server and client-side. As a result, the loading speed of the web page increases, and it boosts your app’s performance.

    Rendering in Vue 

    Vue supports both SSR and CSR just like React and Angular. In Vue CSR, more computing power and memory are required as the complete rendering process takes place on the client side. This can slow down the initial page load times as well as seriously harm the performance of the Vue application. 

    Using Express or NextJS framework, you can manually add the custom SSR functionality which allows server-side rendering in Vue. 

    5.3 Architecture: Angular vs React vs Vue

    The architecture of a framework determines how software applications can be structured and how well it will function. So, let us analyze the architecture of each framework.

    Angular Architecture

    Angular comes with an MVC-based architecture. Because it is also component-based, Angular no longer strictly associates with that pattern in its new releases. Every Angular project is structured into Modules, Components, and Services. 

    Modules are nothing, just various components bundled together. They help you organize your code more efficiently. Modules are either features or functionalities of your application. Every Angular component comes with a Template, a Class to define app logic, and MetaData to tell the component where it can find elements to create and present its view. 

    Each component in Angular contains a Template, a Class that defines the application logic, and MetaData to tell components where they can find the elements to create and present its view. Components are written in HTML and use directives to add special behavior to the elements of your applications. 

    Services consist of the code that is required by various components across the application. After all, they work for components to fetch necessary data and validate the inputs. With such a well-organized architecture, there is no doubt that Angular enables developers to create large and complex web applications.

    React Architecture

    It is easy to use React as you only need a few lines of code to get started. The reason behind this is the simple component-based architecture of the framework. Being a UI library, React offers different kinds of UI components that you can use to build websites and React applications. 

    These components are independent and reusable. They have their own logic and can control their own rendering. With props as input, React components produce elements as outputs which are displayed to the users. 

    React consists of a Virtual DOM that helps improve your app’s speed and responsiveness. Whenever a component changes, they are first implemented in the Virtual DOM which helps find out the most effective way to update the real web pages. 

    Moreover, React comes with JavaScript XML that allows developers to effectively combine both JavaScript and HTML code to create intuitive UI elements for your application.

    Vue Architecture

    VueJS has a simple architecture because all of its components are small, self-contained, and reusable. The architectural pattern of the Vue framework was partly inspired by the MVVM model but Vue doesn’t strictly adhere to it. 

    With Vue, your work will be mostly focused on the ViewModel Layer. The data processing in the framework is carried out in a way that supports the rendering of an updated View. All the relevant HTML, JavaScript, and CSS code of your app exists in Single File Components with a .vue extension which are stored in a single file. 

    If you are working on a Vue project, especially a large one, you have to use these SFCs to organize your code well. Vue is a reactive framework. Whenever the data changes, the relevant components of your app know that they need to be updated. Because in Vue, your app data is tied to its components. 

    This is why using Vue is very easy. Additionally, it has a Virtual DOM just like React. So it’s fast and highly performant as well.

    5.4 Ecosystem

    Angular offers the NgRx project for its state management and this is inspired by Redux. Angular has started offering Angular Material which guides the developers in creating Angular applications with the use of the right Material Design. It enables developers to create cross-platform apps with the use of NativeScript. Angular is also a part of the well-known MEAN stack that is a combination of Angular with ExpressJS, MongoDB, and NodeJS.

    React’s popularity makes it easy for web app developers to find react-based components and elements for the development of web interfaces. Besides, React’s ecosystem also includes React Native which enables the developers to create native Android and iOS apps. React is a part of the MERN stack, which is a combination of React with ExpressJS and NodeJS.

    Vue can use Redux but there are no official bindings between these two. Vuex is the official state management library of Vue. This framework enables developers to use a wide range of components offered by the community to create applications.

    5.5 Tools used in Angular React and Vue Development

    Loads of tools are available in the market that developers can leverage to deliver peak performance and elevated user experience. Some tools are framework-agnostic and can be used with all frameworks for similar purposes. Meanwhile, some tools are framework-specific that cater to the specific requirements of the framework. Let us take a look at the toolkit of our contenders. 

    Tools in Angular 

    • Ng-Inspector: When it comes to developing and debugging cross-browser angular applications, developers prefer to use Ng-Inspector. It adds an auditor sheet in the browser to track the apps. 
    • ng2-charts: This is a charting library that allows you to integrate Chart.js with your Angular app. It offers a variety of charts like bar, donut, line, and pie charts. The bundle size of ng2-charts is 18.2kb minified and 5.9kb gzipped. 
    • Angular-GETTEXT: If you need a language translating tool then Angular-gettext could come in handy. This open-source tool can help you translate everything that is in English. 
    • ng-animate: It is an animation module providing some flexible animations and transitions to make the user interface of your Angular application more engaging and interactive. The bundle size of this tool is 27.9kb minified and 3.3kb gzipped. All the animations offered from ng-animate are completely reusable.
    • Videoangular: It is a free-to-use and one-stop solution for all video-related requirements in your Angular application. Videangualr allows you to easily install an HTML5-based video player in your mobile and desktop apps.

    Tools in React 

    • Create React App: Setting up a project with React was very challenging. Therefore, Google developed this boilerplate project. Create React App is a tool that can help you set up everything you need for your React development project with a single command.
    • Zustand: Although React offers powerful state management solutions such as MobX and Redux, they are heavyweight. As an alternative, React also provides a lightweight state management solution called Zustand. It uses minimal API to eradicate all the complexities of state management. Zustand comes with a bundle size of 3kb minified and 1.1kb gzipped. 
    • React Hook Form: Specifically designed to streamline the form development process for React applications, React Hook Form is a form management and validation library. This robust library is also lightweight as its bundle size is 26.6kb minified and 9.6kb gzipped. 
    • SWR: React provides remote data fetching functionalities thanks to this React Hook library. Features such as pagination, error handling, caching, prefetching, and revalidation are available in SWR. It also supports static site generation and server-side rendering. The bundle size of SWR is 10kb minified and 4.4kb gzipped. 
    • React Belle: A React library that provides reusable components such as Card, Toggle, Button, Select, and more. Components in React Belle are easy to configure or customize. It adheres to ARIA accessibility standards as well. 

    Tools in Vue 

    • VueX: It is a one-stop solution for all your state management problems in Vue. Developers can also leverage it to ensure predictable state modifications. 
    • Vue Router: This is a feature-rich tool from Vue for Routing. It enables the Vue developers to create reusable components. Vue Routing makes it easy for users to navigate between different web pages in the same application. 
    • Vuelidate: Vue offers a lightweight library with a bundle size of 12.4kb minified and 3.7kb gzipped. Its small size is helpful as it doesn’t put much strain on the overall size of the application and leaves only a small footprint. Vuelidate simplifies the way to manage form validation. 
    • ViteJS: It is a build tool used to ensure fast build times and rapid HMR. Using it helps maximize the potential of native browser APIs and ES modules. 
    • Pinia: WIth a bundle size of 21.2kb minified and 7.6kb gzipped, Pinia is a state management solution for the Vue framework. 

    5.6 Optimization Techniques: Angular vs React vs Vue

    Let us now compare the optimization methods these frameworks use to boost the efficiency of their code. 

    Optimization Techniques in Angular Development 

    • Ahead of Time compilation: It reduces the browser’s workload during runtime which helps enhance the performance. 
    • OnPush change detection strategy: It is an approach where you check the component only when its input or output changes. Preventing unnecessary component re-renderings boosts your app performance. 
    • Unsubscribing Observables: You need Observables for asynchronous programming. Once your task is completed, make sure you unsubscribe from Observables properly because they continuously emit events that can harm your app’s performance.

    Optimization Techniques in React Development 

    • Use React Memoization: You can’t afford re-rendering expensive function calls every time. So, use memoization through useMemo Hook to cache the results of your expensive function call. Caching the results will help you ensure that the results are returned every time they are requested unless there are some changes in the dependencies of the function. 
    • Immutable data structures: Leverage immutable data structures to improve the efficiency of your state updates. This optimization technique is largely used to enhance the performance of large applications that have a complex state.

    Optimization Techniques in Vue Development 

    • Lazy loading: You can use LazyLoad routers and their correlated dependencies using the Vue Router. The defineAsyncComponent method also allows you to LazyLoad specific components. 
    • Optimize event handling: Events such as @mouseover and window.scroll can cause some serious performance hits. However, optimizing the event management mechanism allows you to improve the performance. You can limit the number of time events being processed by using the debounce button.

    5.7 Migrations

    When it comes to migration, Angular is a framework that comes with new major updates every six months. Angular also takes six months before releasing any major API. This means that Angular developers get the time of two release cycles in a year and they can make required changes as per this release cycle. 

    In comparison with Angular, React is called a stable framework and because of this companies like Airbnb and Twitter use it. React comes with new upgrades that can be accessed through react-codemod scripts which makes migration a very easy process. 

    Vue has come with a new Vue 3 version but there is not much difference between Vue 2 and Vue 3 which means that almost 90% of the APIs are the same in these versions and this makes migration very easy. Besides, Vue also offers Vue 1 to Vue 2 migration tool which helps developers to assess the app’s status. 

    5.8 Performance and Memory

    The performance of a web app completely depends on the framework. This is why developers check the web frameworks’ scalability (how well it can handle larger-scale projects), integrability, and robustness before choosing one. In this Angular vs React vs Vue 2022 comparison, the performance can be tested as per the framework’s DOM and JS framework benchmark.

    Angular relies on real DOM for performance, while React and Vue functions use virtual DOM. In this case, when any frontend framework depends on virtual DOM, it saves the trouble of re-rendering/repainting the app which eventually makes the web app quicker.

    To get a clear idea about the performances of these three frameworks, check out the performance graphs given below.

    Angular Performance

    Angular Performance

    React Performance

    React Performance

    Vue Performance

    Vue Performance

    5.9 Angular vs React vs Vue Startup Time Comparison

    When it comes to the comparison between these three JavaScript frameworks for their startup time, there is a general thought amongst the techies that Vue would be the winner for startup time as the small size of this framework enables them to decrease the startup time tremendously. This eventually helps in having a robust application.

    Whereas, the developers might get the same result while using React for the web app development process. But this is not the case with the Angular framework as it is very heavy in size.

    5.10 Learning Curve

    Angular is known as a framework that comes with the most complex project structure. And this is because it is a fully-grown front-end framework that relies on more concepts. Angular supports services, components, and modules. In this framework, it is expected to write and design the code in a specific manner which helps the project to be maintainable when it scales up. Besides this, to work with Angular, the developer must be able to write code in TypeScript. 

    React framework is the least complex of these three. And the reason behind it is that the developer just needs to import the library, then they can start writing a React application. Besides this, React apps are component-based and this means that they don’t just render some elements on the page.

    Like Angular, Vue is also a bit of a complex framework. It can be used as a library to define components that must be used throughout your HTML. The majority of the Vue projects come with a root component named App. When it comes to Vue’s syntax, the one thing that developers need to learn is Vue’s template syntax which is similar to HTML. 

    This shows that the learning curve with React is very easy and smooth in comparison to React and Vue.

    5.11 Sample Application Development

    Angular

    Prerequisites: Install Node and Angular CLI in your system.

    Step 1: Create an Angular app with the following command.

    > ng new to-do-list
    

    Move to the project directory using the following command

    > cd to-do-list
    

    Step 2: Create an interface for To-do Item

    export interface ToDoItem { 
      task: string; 
      isCompleted: boolean; 
    }
    

    Step 3: Create 3 components in src folder using the following commands:

    > ng generate component todo  
    > ng generate component form 
    > ng generate component todolist
    
    1. Create a Todo Component which contains logic to list down the to-do items.
    2. Create a Form component which contains logic to add a new task 
    3. Create a TodoList component which contains logic for Listing, Mark as Complete, and Delete the task.

    1. ToDo component:

    This component is responsible for displaying individual to-do item along with a delete button and a checkbox to mark an item as complete. 

    template file: We have used a <p> to display the title, a check box to mark the completion of the task, and a delete button.

    {{ title }}

    Delete

    ts file : ts file contains a 2 input properties that is title and isCompleted , along with this there is a delete method which is emits the event to parent component.

    import { Component, EventEmitter, Input, Output } from '@angular/core'; 
    import { CommonModule } from '@angular/common'; 
    @Component({ 
      selector: 'app-to-do', 
      standalone: true, 
      imports: [CommonModule], 
      templateUrl: './to-do.component.html', 
      styleUrl: './to-do.component.css', 
    }) 
    export class ToDoComponent { 
      @Input() title: string = ''; 
      @Input() isCompleted: boolean = false; 
      @Output() deleteTodoItem = new EventEmitter(); 
     
      onDelete(): void { 
        this.deleteTodoItem.emit(); 
      } 
    }
    

    2. to-do-list: display ToDo-list

    template file: use *ngFor directive to iterate each element in the toDoList.

    ts file: ts file takes to-do list as input and a delete method which emits the event to the parent component.

    import { Component, EventEmitter, Input, Output } from '@angular/core'; 
    import { ToDoComponent } from '../to-do/to-do.component'; 
    import { CommonModule } from '@angular/common'; 
    import { ToDoItem } from '../../ToDoItem'; 
    @Component({ 
      selector: 'app-to-do-list', 
      standalone: true, 
      imports: [ToDoComponent, CommonModule], 
      templateUrl: './to-do-list.component.html', 
      styleUrl: './to-do-list.component.css', 
    }) 
    export class ToDoListComponent { 
      @Input() toDoList: ToDoItem[] = []; 
      @Output() deleteItem = new EventEmitter(); 
     
      deleteTodoItem(todoItem: any): void { 
        this.deleteItem.emit(todoItem); 
      } 
    }
    

    3. Form component

    Template file: contains an input element to store value of to-do task and an add button

    Add

    Ts file: There is a method to push item to parent component so that it can be added to to-do list.

    import { ToDoItem } from './../../ToDoItem'; 
    import { Component, EventEmitter, Output  } from '@angular/core'; 
    import { FormsModule } from '@angular/forms'; 
    @Component({ 
      selector: 'app-form', 
      standalone: true, 
      imports: [FormsModule], 
      templateUrl: './form.component.html', 
      styleUrl: './form.component.css', 
    }) 
    export class FormComponent { 
      @Output() addTodoItem = new EventEmitter(); 
     
      toDoItem: ToDoItem = { task: '', isCompleted: false }; 
     
      onAddTodoItem() { 
        this.addTodoItem.emit(this.toDoItem); 
        this.toDoItem = { task: '', isCompleted: false }; 
      } 
     
    }
    

    4. App component:

    To-Do List


    Ts file: implement logic to add and delete item from to-do list.

    import { Component } from '@angular/core'; 
    import { RouterOutlet } from '@angular/router'; 
    import { ToDoListComponent } from '../Components/to-do-list/to-do-list.component'; 
    import { FormComponent } from '../Components/form/form.component'; 
    import { ToDoItem } from '../ToDoItem'; 
    import { CommonModule } from '@angular/common'; 
    @Component({ 
      selector: 'app-root', 
      standalone: true, 
      imports: [RouterOutlet, ToDoListComponent, FormComponent, CommonModule], 
      templateUrl: './app.component.html', 
      styleUrl: './app.component.css', 
    }) 
    export class AppComponent { 
      title = 'todo-list-app'; 
      toDoList: ToDoItem[] = [ 
      ]; 
     
      addTodoItem(item: ToDoItem) { 
        this.toDoList.push(item); 
      } 
     
      deleteTodoItem(todoItem: any): void { 
        this.toDoList = this.toDoList.filter((item) => item !== todoItem); 
      } 
    }
    

    Step 4: Now Add some CSS. Create an App.css file in the src folder and write the code to include CSS.

    Step 5: Run your application using the following command:

    npm start 
    

    Step 6: Test your application in the browser, by adding/deleting a task and marking the task as complete.

    To-Do List
    To-Do List

    Folder Structure: 

    Folder Structure

    ReactJS

    Prerequisites: Presence of Node.js and React is required in the system.

    Step 1: Create a react app with the following command. 

    npx create-react-app
    

    Step 2: Now, we will create components for our Todo application. 

    • Create a Todo Component which contains logic to list down the to-do items. 
    • Create a Form component which contains logic to add new task
    • Create a TodoList component which contains logic for Listing, Mark as Complete, and Delete the task.

    Create a Todo.js file in components and write the following code in the same. 

    import React from "react";
    
    const Todo = ({ text, todo, completeHandler, editHandler, deleteHandler }) => {
      return (
        
  • {text}
  • ); }; export default Todo;

    Create a Form.js file in components and write the following code in the same. 

    import React, { useEffect, useState } from "react";
    
    const Form = ({ todos, setTodos, editTodo, setEditTodo }) => {
      const [todoText, setTodoText] = useState("");
    
      useEffect(() => {
        if (editTodo) {
          setTodoText(editTodo.text);
        }
      }, [editTodo]);
    
      const handleSubmit = (e) => {
        e.preventDefault();
        if (editTodo) {
          setTodos(
            todos.map((item) => {
              if (item.id === editTodo.id) {
                return {
                  ...item,
                  text: todoText,
                };
              }
              return item;
            })
          );
          setTodoText("");
          setEditTodo(null);
        } else {
          setTodos([
            ...todos,
            { text: todoText, completed: false, id: Math.random() * 1000 },
          ]);
          setTodoText("");
        }
      };
    
      return (
        
           setTodoText(e.target.value)}
          />
          
        
      );
    };
    
    export default Form;
    

    Create a TodoList.js file in components and write the following code in the same. 

    import React from "react";
    import Todo from "./ToDo";
    
    const TodoList = ({ todos, setTodos, setEditTodo }) => {
      const deleteHandler = (id) => {
        setTodos(todos.filter((el) => el.id !== id));
      };
    
      const completeHandler = (id) => {
        setTodos(
          todos.map((item) => {
            if (item.id === id) {
              return {
                ...item,
                completed: !item.completed,
              };
            }
            return item;
          })
        );
      };
    
      const editHandler = (id) => {
        const editItem = todos.find((item) => item.id === id);
        setEditTodo(editItem);
      };
    
      return (
        
      {todos.map((todo) => ( ))}
    ); }; export default TodoList;

    Step 3: Now, open app.js file in src folder and Write the following code in the same.

    import React, { useState } from "react";
    import "./App.css";
    import Form from "./components/Form";
    import TodoList from "./components/TodoList";
    
    const App = () => {
      const [todos, setTodos] = useState([]);
    
      return (
        
    To-do List
    ); }; export default App;

    Step 4: Now Add some CSS. Create an App.css file in the src folder and write the code to include CSS. you can refer the same at:

    * {
      margin: 0;
      padding: 0;
      box-sizing: border-box;
    }
    
    body {
      background-image: linear-gradient(120deg, #f6d365 0%, #fda085 100%);
      color: white;
      font-family: "Poppins", sans-serif;
      min-height: 100vh;
    }
    
    header {
      font-size: 3rem;
      padding-top: 4rem;
      font-weight: 600;
    }
    
    header,
    form {
      min-height: 15vh;
      display: flex;
      justify-content: center;
      align-items: center;
    }
    
    form input,
    form button {
      padding: 0.5rem;
      font-size: 2rem;
      border: none;
      background: white;
    }
    
    form input:focus {
      outline: none;
    }
    
    form button {
      color: #ff6f47;
      background: #f7fffe;
      cursor: pointer;
      transition: all 0.3s ease;
    }
    
    form button:hover {
      background: #ff6f47;
      color: white;
    }
    
    .todo-container {
      display: flex;
      justify-content: center;
      align-items: center;
    }
    
    .todo-list {
      min-width: 30%;
      list-style: none;
    }
    
    .todo {
      margin: 0.5rem;
      background: white;
      font-size: 1.5rem;
      color: black;
      display: flex;
      justify-content: space-between;
      align-items: center;
      transition: all 1s ease;
    }
    
    .todo li {
      flex: 1;
    }
    
    .trash-btn,
    .complete-btn,
    .edit-btn {
      background: rgb(212, 11, 14) ;
      color: white;
      border: none;
      padding: 1rem;
      cursor: pointer;
      font-size: 1rem;
      width: 48px;
    }
    
    .complete-btn {
      background: #ff6f47 ;
    }
    
    .edit-btn {
      background: rgb(11, 212, 162);
    }
    
    .todo-item {
      padding: 0rem 0.5rem;
    }
    
    .fa-trash,
    .fa-check,
    .fa-times {
      pointer-events: none;
    }
    
    .fall {
      transform: translateY(10rem) rotateZ(20deg);
      opacity: 0;
    }
    
    .completed {
      text-decoration: line-through;
      opacity: 0.5;
    }
    
    .fa-pen { 
      font-size: 25px;
    }
    

    Step 5: Update the index.js and index.css files as per the mentioned repository. 

    Step 6: Update index.html file of public folder as per the mentioned repository.

    Add below scripts before title

    
      
        
    
    

    Step 7: Run the application using the following command. 

    npm start
    

    Step 8: A new window in the browser will pop up. Add a few tasks here.

    To-do List
    To-do List

    Folder Structure:

    Folder Structure

    VueJS

    Prerequisites: Presence of Node.js and Vue is required in the system. 

    Step 1: Create a new Vue app with the following command. Also, select version 3 for our application.

    vue create vuetify-todo
    

    Step 2: Now install the vuetify package for better UI so run the command below in the terminal.

    npm install vuetify
    

    Step 3: Install router package with the help of following command. 

    npm install vue-router
    

    Step 4: Create router folder within src folder. Also create index.js file within router folder and add the following code. 

    import { createRouter, createWebHashHistory } from 'vue-router'
    import Todo from '../views/Todo.vue'
    
    const routes = [
      {
        path: '/',
        name: 'Todo',
        component: Todo
      }
    ]
    
    const router = createRouter({
      history: createWebHashHistory(),
      routes
    })
    
    export default router
    
    

    Step 5: Now we can edit the code in the App.vue file for route. Removed all the preloaded code and replaced it with the following.

     
    

    Step 6: Update the “main.js” file with the following code.

    import { createApp } from 'vue'
    import App from './App.vue'
    import router from './router'
    import vuetify from './plugins/vuetify'
    import { loadFonts } from './plugins/webfontloader'
    
    loadFonts()
    
    createApp(App)
      .use(router)
      .use(vuetify)
      .mount('#app')
    

    Step 7: Create “Views” folder in the “src” folder. Create a “Todo.vue” file in this folder.

    
    
    
    
    

    Step 8: Run the application using the below command.

    npm run serve
    

    Step 9: Output:

    Output
    Output
    Output
    Output

    Folder Structure:

    Folder Structure

    6. Top Companies Using React

    Here is the list of the top brands that use React for frontend development –

    • Yahoo
    • Instagram
    • Facebook
    • WhatsApp
    • New York Times

    Further Reading on Companies That Use React

    7. Top Companies Using Angular

    Here is the list of the top brands that use Angular for the front-end development –

    • Microsoft Office
    • Gmail
    • Forbes
    • Deutsche Bank
    • PayPal

    Further Reading on Companies That Use Angular

    8. Top Companies Using Vue

    Here is the list of the top brands that use Vue for the frontend development –

    • Xiaomi 
    • Reuters
    • Adobe
    • Grammarly
    • Behance

    Further Reading on Companies That Use Vue

    9. Tabular Comparison: Angular vs React vs Vue

    Categories Angular React Vue
    Type It is a framework. It is a rich library to create UI. It is a library.
    Maintained By Google maintains this framework. Facebook maintains this library. Evan You, a former Google employee, and his core team maintains this library.
    Initial Release September 2016 March 2013 February 2014
    Development Approach It is based on TypeScript. It is based on JavaScript. It is based on HTML and JavaScript.
    Ideal For It is ideal for creating large-scale apps that have rich features. It is ideal for creating user interfaces based on UI components. It is ideal for creating single-page apps.
    Developer-friendly Angular embraces a structure-based approach. It ensures flexible development. It demands a focus on the separation of concerns.
    Written In TypeScript JavaScript JavaScript

    10. Conclusion

    As seen in this blog, JavaScript frameworks have a huge family. Each of these frontend frameworks and libraries offers the best results when it comes to creating applications, solving issues, or adding new functionalities to current web apps. All three frameworks compared here are different from each other. Angular, React, and Vue are known as the top players among front-end JavaScript frameworks.

    The Angular framework is used by experienced developers for creating apps with extensive structures and this framework works best when it comes to building progressive web apps and hybrid mobile applications.

    React developers use React to create dynamic websites with flawless functionalities. It also helps in creating native mobile apps (using react native framework).

    Vue combines the best features of Angular and React. It helps in creating single page applications.

    This proves that these three JavaScript frameworks perform magic while creating user interfaces and offer the best solutions for robust web development. But which one to choose for your next project depends on the software development environment, the flexibility of the team working, and the type of project they are working on.

    FAQS

    Which is better Vue or React or Angular?

    Vue is easier to learn compared to React and Angular because it is a progressive framework. Then comes React. It is more difficult to learn than Vue but easier than Angular as it is only a UI library. At last, Angular is the most difficult to learn as it is a full-fledged solution for developing complex applications.

    Is Vue faster than Angular?

    Angular is a heavyweight framework that offers various types of mechanisms. Meanwhile, Vue is a lightweight framework that focuses on the View of the app’s architecture. It also uses Virtual DOM which further boosts the app’s performance. So, you can say that Vue is faster than Angular.

    Why choose Angular over React or Vue?

    The only reason you need to choose Angular over Vue and React is because it is a full-fledged framework. Meanwhile, Vue is a progressive framework and React is just a UI library. You can easily leverage Angular to build a large range of applications from single-page apps to enterprise-grade apps.

    The post Angular Vs React Vs Vue: Which One To Choose appeared first on TatvaSoft Blog.

    ]]>
    https://www.tatvasoft.com/blog/angular-vs-react-vs-vue/feed/ 1
    JavaScript vs TypeScript : Key Comparison https://www.tatvasoft.com/blog/javascript-vs-typescript/ https://www.tatvasoft.com/blog/javascript-vs-typescript/#respond Tue, 13 Dec 2022 07:37:19 +0000 https://www.tatvasoft.com/blog/?p=9318 In today’s time, for every business organization, a website is created. The use of websites has extensively increased. As per the survey by Stack Overflow, JavaScript and TypeScript fall into the list of the most popular languages for developing websites.

    The post JavaScript vs TypeScript : Key Comparison appeared first on TatvaSoft Blog.

    ]]>

    Key Takeaways

    1. TypeScript is a superset of JavaScript. It is a modern age language and provides better developer experience.
    2. TypeScript is better than JavaScript in terms of code maintainability, advanced language features, productivity, project scalability, etc.
    3. JavaScript is easy to learn, and probably the best choice for small scale projects while TypeScript requires basic knowledge of Javascript to learn and more suitable for large and complex projects.
    4. At the time of compilation, the TypeScript compiler compiles a TypeScript file to a JavaScript file, which the browser understands.
    5. TypeScript is not the whole replacement of JavaScript. It is only a more feature- rich and technically sound way to write JavaScript.

    In today’s time, for every business organization, having their own website is important. The use of websites has extensively increased. As per the survey by Stack Overflow, JavaScript and TypeScript fall into the list of the most popular languages for developing websites.

    JavaScript, usually referred to as JS, is a high level and object oriented programming language for augmenting HTML web pages and to create web applications, while TypeScript is a superset of JavaScript to create larger web applications. In this blog, we will learn about both the languages and go through the comparison of JavaScript vs TypeScript, to understand the major differences between them, after which a developer can come to a conclusion on which one to choose for his next project. 

    1. JavaScript vs TypeScript (Comparison Table)

    AspectsTypeScriptJavaScript
    Developed ByTypeScript is developed by Microsoft in 2012.JavaScript is developed by Brendan Eich (Netscape) in 1995.
    DefinitionTypeScript is a popular object-oriented programming language and is known as a superset to JavaScript.JavaScript is a widely used scripting language that comes with first-class functions which help developers to create dynamic web pages.
    EcosystemTypeScript is a powerful and intuitive language that comes with the support of static typing.JavaScript is a simple language that has the ability to optimize code for compatibility.
    Data BindingTypeScript programming language uses concepts like types and interfaces to define the data that is being used.There is no such notion with JavaScript.
    TypingTypeScript is a strongly typed language.JavaScript is a loosely typed language.
    CompilationTypeScript code needs to be compiled by typescript compiler before being executed by the browser.JavaScript does not require compilation. It can be directly executed by the browser.
    Client-Side or Server-SideTypeScript is used for client-side app development.JavaScript is used for both client-side and server-side app development.
    Learning CurveTypeScript doesn’t have a smooth learning curve. For this language, developers require scripting knowledge.JavaScript comes with a flexible learning curve.
    Files ExtensionsThe file extensions of TypeScript are .tsx and .ts.The file extension of JavaScript is .js.
    Npm PackagesTypescript comes with numerous npm packages.JavaScript offers form code and the alternative to search code without any build step.
    PrototypingTypeScript offers a Prototyping feature.JavaScript doesn’t support prototyping.
    CommunityTypeScript comes with a smaller community of software engineers. You can determine this by checking the number of questions tagged with TypeScript on StackOverflow.JavaScript comes with a large community of software engineers. You can determine this by checking the number of questions tagged with JavaScript on StackOverflow.
    Companies and WebsitesClever, Asana, and Screen award.Instagram, Airbnb, and Codecademy.

    2. Why was TypeScript Developed?

    When JavaScript was introduced in the web app development world, it was just a client-side programming language, but with time developers learned that it can also be used as a server-side programming language. But it became very difficult for developers to use JavaScript for backend coding because of its complexity and it wasn’t able to stand up to the object-oriented programming language which resulted in the development of TypeScript. TypeScript programming language was basically born to bridge the gap between server-side programming and object-oriented techniques.

    3. Advantages of Using TypeScript over JavaScript

    Some of the major benefits of TypeScript are – 

    • TypeScript is a programming language that can easily identify compilation errors at the time of the app development process and this helps the number of runtime errors has decreased.
    • This programming language is just like JavaScript which means that it comes with all the features just as JavaScript and the additional one is ES6 features. 
    • ES6 comes with advanced features like arrow functions, let and const KWs, default parameters, etc.

      For an example;

      import * as _ from 'lodash'; 
      export const reverseFn = () => console.log(_.reverse(['x', 'y', 'z']));

      When we use compiler option ‘–module CommonJS’, we get

      "use strict"
      exports.__esModule = true;
      exports.reverseFn  = void 0;
      var _ = require("lodash");
      var reverseFn = function () { return console.log(_.reverse(['x', 'y', 'z'])); };
      exports.reverseFn  = reverseFn;
      
    • It comes with the support of static/strong typing. And this means that in this programming language the type correctness can be easily checked at compile time. 
    • TypeScript supports JS libraries and API documentation.
    • TypeScript also provides refactoring suggestions:
      • Take an example of the below code;
      • const employeeData = (data: string) => {
            const employee: {name: string, yearOfJoining: number, country: string}[] = [];
            const errors: string[] = [];
        
            return {employee, errors};
        };
        
        
        const exampleData = `
            Mohit Patel, 2019, INDIA;
            Vikash, 2016, USA;
            Invalid entry
        `;
        
        const result = employeeData(.......);
        
      • In the below TypeScript snippet, the IDE suggests an autocompletion of the names of the keys inside the function’s (employeeData’s) return value:
      • TypeScript Snippet

    4. Advantages of Using JavaScript over TypeScript

    Some of the major benefits of JavaScript are – 

    • JavaScript is a very popular interpreted language that helps the developers reduce the compilation time and the execution is also quick with this language. 
    • In this comparison of JavaScript vs TypeScript, JavaScript is easy to learn and understand which is a huge benefit for the newbies.
    • JavaScript is a language that works great with other programming languages which means that developers can use it while working on any type of application.
    • As per Google Trends statistics, in September 2024, JavaScript’s interest over time score is 85 and that of TypeScript is 16.

    5. When to Choose JavaScript?

    In this debate of JavaScript vs TypeScript, JavaScript programming language can be chosen in the following scenarios – 

    • Stable testing workflow: Having a JavaScript team that is already applying test-driven app development features is very beneficial than swapping to TypeScript.
    • Build tools needed: Using JavaScript is a good option when the build tools are required. 
    • Small assignments: JavaScript is the best option for the development team when they are working on a small project.
    • Supported framework: When the app development project requires support to form a different framework, using JavaScript is considered as it supports various frameworks and libraries. This means that with JavaScript the developers can easily create web applications and streamline the software development process.

    6. When to Choose TypeScript?

    TypeScript programming language can be chosen in the following scenarios – 

    • Huge projects or many developers: If the team of developers is working on a huge project that needs several software engineers and additional communicating APIs to maintain the project, TypeScript is the best alternative. 
    • Compile-time type checking: When the development team prefers compile-time error checking, TypeScript is considered as it helps in executing compile-time validation and run-time type confirmation.
    • Functioning with a new library or framework: When it comes to working with a new framework or library, the use of TypeScript is considered. 

    7. Why Should One Migrate the Project to TypeScript?

    If the business owner or the hired software development company of any business organization is planning to migrate the project to TypeScript, it must be done only if the codebase of the project is large and complex. Also if there are higher chances of errors occurring in the codebase of the project, TypeScript must be considered. However, it will be great if the team resolves errors at the compilation time. And this is when TypeScript can be used by the team to reduce errors during compile time. Besides this, the best part of migrating the project into TypeScript is that the entire Java codebase of the project may be reused as it is.

    8. Will TypeScript Replace JavaScript?

    TypeScript replacing JavaScript entirely isn’t possible as it is a different programming language except that it inherits some of JavaScript’s basic nature. This is why JavaScript cannot ever be replaced. JavaScript is one of the most widely useful, popular, and fundamental technologies in the ecosystem of software development. Developers can use it for both client-side and server-side app development processes. While on the other hand, TypeScript cannot be directly executed in web browsers. It is a language that trans compiles to JavaScript. JavaScript is easier to debug the application and compile while the web browser carries out the execution process. 

    This means that both these languages have their own pros and cons, but when it comes to TypeScript replacing JavaScript, it is not possible. 

    9. Conclusion

    As seen in this JavaScript vs TypeScript comparison, both of them are popular programming languages that come with unique features for the app development process. TypeScript is a language that is suitable for developers who want to develop readable code. And this language offers various live-bugs checking and static typing features. On the other hand, JavaScript is a popular programming language that developers use with HTML to improve the web pages’ quality and it comes with multi-web browser support. So, when it comes to choosing between JavaScript vs TypeScript, the choice can be as per the developer’s requirements for the project and the project type.

    More Details about JavaScript:

    JavaScript is known as one of the widely used programming languages for web development . It is an object-oriented, lightweight scripting language that is used for cross-platform app development processes by web development companies. JavaScript is used for creating client-side dynamic and interactive web pages. The programs in this programming language are known as scripts and these scripts are written on HTML pages. The scripts are automatically executed as the page loads. 

    History of JavaScript:

    JavaScript programming language was developed by a programmer named Brendan Eich from Netscape Communications Corporation. This language was developed in September 1995 and was called Mocha when it was introduced to the world. After gaining popularity in the market and becoming the best scripting tool, it was renamed JavaScript. And in November 1996, JavaScript was submitted to ECMA by Netscape. 

    JavaScript Vesrion Timeline

    Features of JavaScript:

    • JavaScript is a popular cross-platform language.
    • It is used for both server-side and client-side app development processes. 
    • JavaScript is a dynamic language which means that it is powerful and flexible.
    • It is an easy-to-learn language. 
    • The app developer can get ‘the great freedom’ to do whatever he wants to with an object in this language. 
    • JavaScript comes with a strong testing workflow and added dependencies.
    • JavaScript helps developers to create interactive web pages.

    JavaScript Code Example:

    
    

    More Details about TypeScript:

    TypeScript is one of the most popular open-source object-oriented programming languages. This programming language is known as a strongly typed superset of JavaScript

    What is TypeScript?

    TypeScript programming language is created and maintained by Microsoft under the license, Apache 2. TypeScript cannot be directly run on the web browser, it first needs to be compiled in a compiler and converted into plain JavaScript code. . The extension of the TypeScript source file is “.ts”.

    TypeScript has 84.3k stars and 11k forks on GitHub. Besides, it is used by 7.4m developers.

    GitHub

    History of TypeScript:

    TypeScript programming language is developed by Anders Hejlsberg. It was originally introduced to the public platform in October 2012. Later on, after two years of its launch and internal development at Microsoft, TypeScript’s new version, TypeScript 0.9 was released in the year 2013. And the most recent version of TypeScript is Version 4.8 which was launched in August 2022. 

    Features of TypeScript:

    • TypeScript is the easiest maintainability app development language.
    • It offers features like code navigation, bug prevention, code discoverability, refactoring, and more. 
    • TypeScript comes with a great productivity level for developers.
    • It offers optional static type annotation.
    • TypeScript programming language supports ES6.
    • It is a programming language that supports classes, subclasses, interfaces, and sub-interfaces.
    • With TypeScript, Rich IDE is available with features like code navigation and autocomplete.
    • It comes with scalable HTML5 client-side development.
    • TypeScript is a class-based object-oriented language that comes with the inheritance of private interfaces and members.

    TypeScript Code Example:

    //Addition of two numbers
    function addNumbers(num1: number, num2: number) { 
        return num1 + num2; 
    } 
    
    var sum: number = addNumbers(1, 8) 
    console.log(sum); //Print the result
    

    The post JavaScript vs TypeScript : Key Comparison appeared first on TatvaSoft Blog.

    ]]>
    https://www.tatvasoft.com/blog/javascript-vs-typescript/feed/ 0