Category: Cheat Sheet

  • Angular Cheat Sheet 2023

    Angular is a TypeScript-based open-source web application framework used to build web and mobile-based applications. This article will go through some of the angular features by explaining some of its core APIs. You can follow this angular cheat sheet to build your project.

    Angular Cheat Sheet:

    We have tried to cover Angular CLI, Angular Lifecycle Hooks, Angular Routing, and much more here.

    1. Angular CLI

    Angular gives us the ability to do a whole lot using their CLI. You can config the entire application by just using the CLI. Here are some of the commands:

    • npm install -g @angular/cli : This command will install the Angular CLI into our local machine using npm.
    • ng new <application name> : This will set up a new Angular application using the ng new command.
    • ng new <application name> --prefix best : This creates a new project and set the project prefix to new.
    • ng new --help: This returns all available Angular command lists.
    • ng lint my-app: This command checks our entire application for any linting warnings.
    • ng lint my-app --fix: If there are any form of linting errors, this command will fix it.
    • ng lint my-app --format stylish : This formats our entire codebase.
    • ng lint my-app --help: This command returns all the available linting command lists.
    • ng add <package name>: This command will use your package manager to download new dependencies and update the project with configuration changes.
    • ng generate component <name>: This will create a new component of our application. We can also use the ng g c <name> shorthand to do this.
    • ng g d <directive name>: This command angular directive.
    • ng g s <service name> : Creates a new Javascript class-based service.
    • ng g p <pipe name>: Generates a new pipe
    • ng g cl <destination> : This will create a new class in the specified directory.
    • ng build: Builds the application for production and stores it in the dist directory.
    • ng serve -o: Serves the application by opening up the application in a browser using any port 4200 or any available port.
    • ng serve -ssl: serves the application using SSL

    2. Angular Lifecycle Hooks

    A component in Angular has a life cycle, several different phases it goes through from birth to death. We can hook into those different phases to get some pretty fine-grained control of our application. Here you can see some Angular Lifecycle Hooks.

    • ngOnChanges: This is called whenever one of the input properties changes.
    • ngOnInit: This is called immediately after ngOnChanges is completed and it is called once.
    • ngOnDestroy: Called before angular destroys a directive or component
    • ngDoCheck: Whenever a change detection is running, this is called.
    • ngAfterContentInit: Invoked after Angular performs any content projection into the component’s view.
    • ngAfterContentChecked: This is called each time the content of the given component has been checked by the change detection mechanism of Angular.
    • ngAfterViewInit This is called when the component’s view has been fully initialized.
    • ngAfterViewChecked: Invoked each time the view of the given component has been checked by the change detection mechanism of Angular.

    3. How Angular Hooks are used

    Always remember that hooks work in a component or directory, so use them in our component, we can do this:

    `class ComponentName {
        @Input('data') data: Data;
        constructor() {
            console.log(`new - data is ${this.data}`);
        }
        ngOnChanges() {
            console.log(`ngOnChanges - data is ${this.data}`);
        }
        ngOnInit() {
            console.log(`ngOnInit  - data is ${this.data}`);
        }
        ngDoCheck() {
            console.log("ngDoCheck")
        }
        ngAfterContentInit() {
            console.log("ngAfterContentInit");
        }
        ngAfterContentChecked() {
            console.log("ngAfterContentChecked");
        }
        ngAfterViewInit() {
            console.log("ngAfterViewInit");
        }
        ngAfterViewChecked() {
            console.log("ngAfterViewChecked");
        }
        ngOnDestroy() {
            console.log("ngOnDestroy");
        }
    }

    4. Component DOM

    Angular comes with DOM features where you can do a whole lot from the binding of data and defining dynamic styles. Let’s take a look at some features:
    Before we dive into the features, a simple component.ts file is in this manner:

    import { Component } from '@angular/core';
    @Component({
        // component attributes
        selector: 'app-root',
        templateUrl: './app.component.html',
        styleUrls: ['./app.component.less']
    })
    export class AppComponent {
        name: 'Sunil';
    }

    5. Let’s look at some template syntax:

    • Interpolation: using {{data to be displayed}} will display dynamic content from the ts file.
    • <button (click)="callMethod()" ... /> : Adding Click events to buttons to call a method defined in the ts file
    • <button *ngIf="loading" ... />: Adding Conditionals to elements. Conditionals have to listen to truthy or falsy values.
    • *ngFor="let item of items": iterate through a defined list of items. Picture this as a for a-loop.
    • <div [ngClass]="{green: isTrue(), bold: itTrue()}"/>: Adding dynamic classes based on conditionals.
    • <div [ngStyle]="{'color': isTrue() ? '#bbb' : '#ccc'}"/>: Adding dynamic styles to the template based on conditions

    6. Component Communication

    Passing data from one component to another can be a little bit tricky in Angular. You can pass data from child to parent, parent to parent, and between two unrelated components:

    • input(): This method helps To pass a value into the child components.
    export class SampleComponent {
    @Input() value: 'Some Data should go in here';
    }

    Child components are registered in parents’ components like this:

    <child-component [value]="data"></child-component>
    • output(): This method Emits an event to the parent component. A bunch of data can be passed into the emitted event which makes it a medium of passing data from child to parent:

    To Emit the event from the child component:

    @Output() myEvent: EventEmitter < MyModel > = new EventEmitter();
    calledEvt(item: MyModel) {
        this.myEvent.emit(item);
    }

    And then the parent component listens to that event:

    <parent-component 
    (myEvent)="callMethod()"></parent-component>

    7. Angular Routing

    Routing is another cool feature of Angular, with the Angular Routing system we can navigate through pages and even add route guards.

    • Component Routing: We can define routes in our application by defining the path and the component to be rendered:
    const routes: Routes = [ 
      { path: 'home', component:HomeComponent }, 
      { path: 'blog/:id', component: BlogPostCompoent }, 
      { path: '**', component: PageNotFoundComponent } 
    ];

    For routing to work, add this the your app.module.ts file:

    RouterModule.forRoot(routes)

    There are situations whereby you want to keep track of what is happening in your routes, you can add this to enable tracing in your angular project:

    RouterModule.forRoot(routes,{enableTracing:true})

    To navigate through pages in Angular, we can use the routerLink the attribute which takes in the name of the component we are routing to:

    <a routerLink="/home" routerLinkActive="active"> Crisis Center</a>

    The routerLinkActive="active" will add an active class to the link when active.

    8. Writing Route Guards

    We can define a guard for route authentication. We can use the CanActivate class to do this:

    class AlwaysAuthGuard implements CanActivate {        
            canActivate() {
                    return true;
            }
    }

    To use this rote guard in our routes we can define it here:

    const routes: Routes = [
      { path: 'home', component:HomeComponent },
      { path: 'blog/:id', component: BlogPostCompoent,canActivate: [AlwaysAuthGuard],  },
        { path: '**', component: PageNotFoundComponent }
    ];

    9. Angular Services

    Angular services come in handy when you can do things like handling HTTP requests and seeding data on your application. They focus on presenting data and delegating data access to a service.

    @Injectable()
    export class MyService {
        public users: Users[];
        constructor() { }
        getAllUsers() {
            // some implementation
        }
    }

    To use this service in your component, import it using the import statement and then register it in the constructor

    import MyService from '<path>'
    constructor(private UserService: MyService) 

    To make things easier, we can use this command to generate service in Angular

    ng g s <service name>

    10. HTTP Service

    Angular comes with its own HTTP service for making HTTP requests. To use it, you have to first of all import it into your root module:

    import { HttpClientModule} from "@angular/common/http";

    After importing it, we can now use it inside our service for making HTTP requests:

    import { Injectable } from '@angular/core';
    import { HttpClient } from '@angular/common/http';
    @Injectable({
        providedIn: 'root'
    })
    export class UserService {
        constructor(private http: HttpClient) { }
        getAllUsers() {
            return this.http.get(`${baseURL}admin/list-users`);
        }
    }

    11. HTTP Interceptors

    An interceptor is a piece of code that gets activated for every single HTTP request received by your application. Picture an interceptor as a middleware in nodejs where an HTTP request made is passed through this piece of code.

    To define an interceptor create a http-interceptor.ts file inside your src directory and add this:

    import { Injectable } from '@angular/core';
    import {
        HttpEvent,
        HttpInterceptor,
        HttpHandler,
        HttpRequest,
        HttpErrorResponse,
        HttpResponse
    } from '@angular/common/http';
    import { Observable } from 'rxjs';
    import { tap } from 'rxjs/operators';
    @Injectable({
        providedIn: 'root'
    })
    export class HttpConfigInterceptor implements HttpInterceptor {
        constructor() { }
        intercept(req: HttpRequest<any>, next: HttpHandler) {
            // Get the auth token from  localstorage.
            const authToken = localStorage.getItem('token');
            // Clone the request and replace the original headers with
            // cloned headers, updated with the authorization.
            const authReq = req.clone({
                headers: req.headers.set('Authorization', authToken)
            });
            // send cloned request with header to the next handler.
            return next.handle(authReq);
        }
    }

    This is a simple interceptor that checks if users have a token in their device’s local storage. If the user does, it will pass the token in all the HTTP headers.

    12. Pipes

    Pipes in Angular give us the ability to transform data into any specific format. For example, you can write a simple pipe that will format an integer to a currency format or format dates to any form.
    Angular comes with some built-in pipes like the date and currency pipe.

    We can define our own custom pipes too by doing this:

    import { Pipe, PipeTransform } from '@angular/core';
    
    @Pipe({ name: 'exponentialStrength' })
    export class ExponentialStrengthPipe implements PipeTransform {
        transform(value: number, exponent?: number): number {
            return Math.pow(value, isNaN(exponent) ? 1 : exponent);
        }
    }

    to use a pipe in our component we can do this:

    {{power | exponentialStrength: factor}}

    13. Bootstrapping:

    import { platformBrowserDynamic } from '@angular/platform-browser-dynamic';
    • Bootstraps the application, using the root component from the specified NgModule.
    platformBrowserDynamic().bootstrapModule(AppModule);
    

    14. NgModules:

    • To import NgModule from @angular/core.
    import { NgModule } from '@angular/core';
    • Defines a module that contains components, directives, pipes, and providers.
    @NgModule({ 
      declarations: …, 
      imports: …, 
      exports: …, 
      providers: …, 
      bootstrap: … 
    }) 
    • List of components, directives, and pipes that belong to this module.
    declarations: [ 
      MyRedComponent, 
      MyBlueComponent, 
      MyDatePipe 
    ]
    • List of modules to import into this module. Everything from the imported modules is available to declarations of this module.
    imports: [ 
      BrowserModule, 
      SomeOtherModule 
    ]
    • List of components, directives, and pipes visible to modules that import this module.
    exports: [ 
      MyRedComponent, 
      MyDatePipe 
    ]
    • List of dependency injection providers visible both to the contents of this module and to importers of this module.
    providers: [ 
      MyService, 
      { provide: … } 
    ]
    • List of components to bootstrap when this module is bootstrapped.
    bootstrap: [MyAppComponent]

    15. Template Syntax:

    • Binds property value to the result of expression firstName.
    <input [value]="firstName">
    • Binds attribute role to the result of expression myAriaRole.
    <div [attr.role]="myAriaRole">
    • Binds the presence of the CSS class extra-sparkle on the element to the truthiness of the expression isDelightful.
    <div [class.extra-sparkle]="isDelightful">
    • Binds style property width to the result of the expression mySize in pixels. Units are optional.
    <div [style.width.px]="mySize">
    • Calls method readRainbow when a click event is triggered on this button element (or its children) and passes in the event object.
    <button (click)="readRainbow($event)">
    • Binds a property to an interpolated string, for example, “Hello Seabiscuit”.
    <div title="Hello {{ponyName}}">

    is equivalent to:

    <div [title]="'Hello ' + ponyName">
    • Binds text content to an interpolated string, for example, “Hello Seabiscuit”.
    <p> 
      Hello {{ponyName}} 
    </p>
    • Sets up two-way data binding.
    <my-cmp [(title)]="name">

    is equivalent to:

    <my-cmp [title]="name" (titleChange)="name=$event">
    • Creates a local variable movieplayer that provides access to the video element instance in data-binding and event-binding expressions in the current template.
    <video #movieplayer …></video> 
    <button (click)="movieplayer.play()"> 
      Play 
    </button>
    • The asterisk (*) character turns the current element into an embedded template.
    <p *myUnless="myExpression"> 
      … 
    </p>

    is equivalent to:

    <ng-template [myUnless]="myExpression"> 
      <p> 
        … 
      </p> 
    </ng-template>
    • Transforms the current value of the expression cardNumber using the pipe called myCardNumberFormatter.
    <p> 
      Card No.: {{cardNumber | myCardNumberFormatter}} 
    </p>
    • The safe navigation operator (?) means that the employer field is optional and if undefined, the rest of the expression should be ignored.
    <p> 
      Employer: {{employer?.companyName}} 
    </p>
    • An SVG snippet template needs an svg: prefix on its root element to disambiguate the SVG element from an HTML component.
    <svg:rect x="0" 
              y="0" 
              width="100" 
              height="100"/>
    • A root element is detected as an SVG element automatically, without the prefix.
    <svg> 
      <rect x="0" 
            y="0" 
            width="100" 
            height="100"/> 
    </svg>

    16. Built-in Directives:

    import { CommonModule } from '@angular/common';
    • Removes or recreates a portion of the DOM tree based on the showSection expression.
    <section *ngIf="showSection">
    • Turns the li element and its contents into a template, and uses that to instantiate a view for each item in list.
    <li *ngFor="let item of list">
    • Conditionally swaps the contents of the div by selecting one of the embedded templates based on the current value of conditionExpression.
    <div [ngSwitch]="conditionExpression">
      <ng-template [ngSwitchCase]="case1Exp"> 
        … 
      </ng-template>
      <ng-template ngSwitchCase="case2LiteralString"> 
        … 
      </ng-template>
      <ng-template ngSwitchDefault> 
        … 
      </ng-template> 
    </div>
    • Binds the presence of CSS classes on the element to the truthiness of the associated map values. The right-hand expression should return {class-name: true/false} map.
    <div [ngClass]="{'active': isActive, 
                     'disabled': isDisabled}">
    • Allows you to assign styles to an HTML element using CSS. You can use CSS directly, as in the first example, or you can call a method from the component.
    <div [ngStyle]="{'property': 'value'}"> 
    <div [ngStyle]="dynamicStyles()">

    17. Forms:

    • Import FormsModule from @angular/forms.
    import { FormsModule } from '@angular/forms';
    • Provides two-way data-binding, parsing, and validation for form controls.
    <input [(ngModel)]="userName">

    18. Class Decorators:

    • Import Directive, … from @angular/core’;.
    import { Directive, … } from '@angular/core';
    • Declares that a class is a component and provides metadata about the component.
    @Component({…}) 
    class MyComponent() {}
    • Declares that a class is a directive and provides metadata about the directive.
    @Directive({…}) 
    class MyDirective() {}
    • Declares that a class is a pipe and provides metadata about the pipe.
    @Pipe({…}) 
    class MyPipe() {}
    • Declares that a class can be provided and injected by other classes. Without this decorator, the compiler won’t generate enough metadata to allow the class to be created properly when it’s injected somewhere.
    @Injectable() 
    class MyService() {}

    19. Directive Configuration:

    • Add property1 property with value1 value to Directive.
    @Directive({ 
      property1: value1, 
      … 
    })
    • Specifies a CSS selector that identifies this directive within a template. Supported selectors include element, [attribute], .class, and :not().
    • Does not support parent-child relationship selectors.
    selector: '.cool-button:not(a)'
    • List of dependency injection providers for this directive and its children.
    providers: [ 
      MyService, 
      { provide: … } 
    ]

    20. Component Configuration:

    @component extends @directive, so the @directive configuration applies to components as well.

    • If set, the templateUrl and styleUrl are resolved relative to the component.
    moduleId: module.id

    List of dependency injection providers scoped to this component’s view.

    viewProviders: [MyService, { provide: … }]

    Inline template or external template URL of the component’s view.

    template: 'Hello {{name}}' 
    templateUrl: 'my-component.html'

    List of inline CSS styles or external stylesheet URLs for styling the component’s view.

    styles: ['.primary {color: red}'] 
    styleUrls: ['my-component.css']

    21. Class Field Decorators For Directives And Components:

    • Import Input, … from @angular/core.
    import { Input, … } from '@angular/core';
    • Declares an input property that you can update using property binding (example: ).
    @Input() myProperty;
    • Declares an output property that fires events that you can subscribe to with an event binding (example: ).
    @Output() myEvent = new EventEmitter();
    • Binds a host element property (here, the CSS class valid) to a directive/component property (isValid).
    @HostBinding('class.valid') isValid;

    Subscribes to a host element event (click) with a directive/component method (onClick), optionally passing an argument ($event).

    @HostListener('click', ['$event']) onClick(e) {…}
    • Binds the first result of the component content query (myPredicate) to a property (myChildComponent) of the class.
    @<a href="https://angular.io/api/core/ContentChild">ContentChild</a>(myPredicate) myChildComponent;
    • Binds the results of the component content query (myPredicate) to a property (myChildComponents) of the class.
    @ContentChildren(myPredicate) myChildComponents;
    • Binds the first result of the component view query (myPredicate) to a property (myChildComponent) of the class. Not available for directives.
    @ViewChild(myPredicate) myChildComponent;
    • Binds the results of the component view query (myPredicate) to a property (myChildComponents) of the class. Not available for directives.
    @ViewChildren(myPredicate) myChildComponents;

    22. Directive And Component Change Detection And Lifecycle Hooks (Implemented As Class Methods):

    • Called before any other lifecycle hook. Use it to inject dependencies, but avoid any serious work here.
    constructor(myService: MyService, …) { … }
    • Called after every change to input properties and before processing content or child views.
    ngOnChanges(changeRecord) { … }
    • Called after the constructor, initializing input properties, and the first call to ngOnChanges.
    ngOnInit() { … }
    • Called every time that the input properties of a component or a directive are checked. Use it to extend change detection by performing a custom check.
    ngDoCheck() { … }
    • Called after ngOnInit when the component’s or directive’s content has been initialized.
    ngAfterContentInit() { … }
    • Called after every check of the component’s or directive’s content.
    ngAfterContentChecked() { … }
    • Called after ngAfterContentInit when the component’s views and child views / the view that a directive is in has been initialized.
    ngAfterViewInit() { … }
    • Called after every check of the component’s views and child views / the view that a directive is in.
    ngAfterViewChecked() { … }
    • Called once, before the instance is destroyed.
    ngOnDestroy() { … }

    23. Dependency Injection Configuration:

    • Sets or overrides the provider for MyService to the MyMockService class.
    { provide: MyService, useClass: MyMockService }
    • Sets or overrides the provider for MyService to the myFactory factory function.
    { provide: MyService, useFactory: myFactory }
    • Sets or overrides the provider for MyValue to the value 41.
    { provide: MyValue, useValue: 41 }

    24. Routing And Navigation:

    Import Routes, RouterModule, … from @angular/router.

    import { Routes, RouterModule, … } from '@angular/router';

    Configures routes for the application. Supports static, parameterized, redirect, and wildcard routes. Also supports custom route data and resolve.

    const routes: Routes = [ 
      { path: '', component: HomeComponent }, 
      { path: 'path/:routeParam', component: MyComponent }, 
      { path: 'staticPath', component: … }, 
      { path: '**', component: … }, 
      { path: 'oldPath', redirectTo: '/staticPath' }, 
      { path: …, component: …, data: { message: 'Custom' } } 
    ]); 
     
    const routing = RouterModule.forRoot(routes);

    Marks the location to load the component of the active route.

    <router-outlet></router-outlet> 
    <router-outlet name="aux"></router-outlet>

    Creates a link to a different view based on a route instruction consisting of a route path, required and optional parameters, query parameters, and a fragment. To navigate to a root route, use the / prefix; for a child route, use the ./prefix; for a sibling or parent, use the ../ prefix.

    <a routerLink="/path"> 
    <a [routerLink]="[ '/path', routeParam ]"> 
    <a [routerLink]="[ '/path', { matrixParam: 'value' } ]"> 
    <a [routerLink]="[ '/path' ]" [queryParams]="{ page: 1 }"> 
    <a [routerLink]="[ '/path' ]" fragment="anchor">

    The provided classes are added to the element when the routerLink becomes the current active route.

    <a [routerLink]="[ '/path' ]" routerLinkActive="active">

    The provided classes and aria-current attribute are added to the element when the routerLink becomes the current active route.

    <a [routerLink]="[ '/path' ]" routerLinkActive="active" ariaCurrentWhenActive="page">

    An interface for defining a function that the router should call first to determine if it should activate this component. Should return a boolean|UrlTree or an Observable/Promise that resolves to a boolean|UrlTree.

    function canActivateGuard: CanActivateFn = 
      ( 
        route: ActivatedRouteSnapshot, 
        state: RouterStateSnapshot 
      ) => { … } 
     
    { path: …, canActivate: [canActivateGuard] }

    An interface for defining a function that the router should call first to determine if it should deactivate this component after a navigation. Should return a boolean|UrlTree or an Observable/Promise that resolves to a boolean|UrlTree.

    function canDeactivateGuard: CanDeactivateFn<T> = 
      ( 
        component: T, 
        route: ActivatedRouteSnapshot, 
        state: RouterStateSnapshot 
      ) => { … } 
     
    { path: …, canDeactivate: [canDeactivateGuard] }

    An interface for defining a function that the router should call first to determine if it should activate the child route. Should return a boolean|UrlTree or an Observable/Promise that resolves to a boolean|UrlTree.

    function canActivateChildGuard: CanActivateChildFn = 
      ( 
        route: ActivatedRouteSnapshot, 
        state: RouterStateSnapshot 
      ) => { … } 
     
    { path: …, canActivateChild: [canActivateGuard], children: … }

    An interface for defining a function that the router should call first to resolve route data before rendering the route. Should return a value or an Observable/Promise that resolves to a value.

    function resolveGuard implements ResolveFn<T> = 
      ( 
        route: ActivatedRouteSnapshot, 
        state: RouterStateSnapshot 
      ) => { … }  
     
    { path: …, resolve: [resolveGuard] }

    An interface for defining a function that the router should call first to check if the lazy loaded module should be loaded. Should return a boolean|UrlTree or an Observable/Promise that resolves to a boolean|UrlTree.

    function canLoadGuard: CanLoadFn = 
      ( 
        route: Route 
      ) => { … } 
     
    { path: …, canLoad: [canLoadGuard], loadChildren: … }

    Free Angular Templates by AdminMart

    Well, I hope you have enjoyed our Angular Cheat Sheet and learned about Angular Lifecycle hooks, routing, and more. It will help while developing your project. Same way, Angular Templates also can help you with your project. As they come with stunningly designed interfaces and ready-to-use components, which can save you time and money. Also, you will be able to find the best Free Angular Templates by AdminMart. You can download that with zero investment and use it in your personal as well as commercial projects.

    If you are looking for Angular Admin Dashboard Template then you can check out below useful Admin Template which can save you time, money, and energy:

    Modernize Angular Material Dashboard


    Also Checkout Other Cheat Sheets:

    Next.js Cheat Sheet

    React Cheat Sheet

    Nuxt Cheat Sheet

    Vue Cheat Sheet

  • React Cheat Sheet: Functional Components Edition

    React Cheat Sheet: Functional Components Edition

    React has evolved significantly since its inception, and with the rise of Hooks, functional components have become the go-to approach for building React applications. This cheat sheet provides an overview of the key concepts, features, and best practices for using functional components in React.

    1. Functional Components Basics

    A functional component is a plain JavaScript function that returns a React element.

    const MyComponent = () => { return
    Hello, World!
    ; };

    2. Using JSX

    JSX is a syntax extension that allows you to write HTML-like code within your JavaScript.

    const MyComponent = () => { return (

    Welcome to React

    ); };

    3. Props

    Props are used to pass data from a parent component to a child component.

    const Greeting = ({ name }) => { return

    Hello, {name}!

    ; }; // Usage

    4. Default Props

    You can define default props for a component.

    const Greeting = ({ name = "Guest" }) => {
      return <h1>Hello, {name}!</h1>;
    };
    

    5. State with useState

    The useState Hook allows you to add state to functional components.

    import { useState } from 'react';
    
    const Counter = () => {
      const [count, setCount] = useState(0);
    
      return (
        <div>
          <p>Count: {count}</p>
          <button onClick={() => setCount(count + 1)}>Increment</button>
        </div>
      );
    };
    

    6. Effect Hook: useEffect

    The useEffect Hook lets you perform side effects in functional components.

    import { useEffect } from 'react';
    
    const DataFetcher = () => {
      useEffect(() => {
        fetch('/api/data')
          .then(response => response.json())
          .then(data => console.log(data));
      }, []); // Empty dependency array means it runs once
    
      return <div>Data fetched. Check console.</div>;
    };
    

    7. Conditional Rendering

    Render different UI elements based on certain conditions.

    const LoginMessage = ({ isLoggedIn }) => {
      return (
        <div>
          {isLoggedIn ? <h1>Welcome back!</h1> : <h1>Please log in.</h1>}
        </div>
      );
    };
    

    8. Lists and Keys

    Render lists of data and use keys to help React identify which items have changed.

    const ItemList = ({ items }) => {
      return (
        <ul>
          {items.map(item => (
            <li key={item.id}>{item.name}</li>
          ))}
        </ul>
      );
    };
    

    9. Event Handling

    Handle events in functional components.

    const Button = () => {
      const handleClick = () => {
        alert('Button clicked!');
      };
    
      return <button onClick={handleClick}>Click Me</button>;
    };
    

    10. Forms and Controlled Components

    Handle form input with controlled components.

    const Form = () => {
      const [value, setValue] = useState('');
    
      const handleChange = (e) => {
        setValue(e.target.value);
      };
    
      const handleSubmit = (e) => {
        e.preventDefault();
        alert(`Submitted value: ${value}`);
      };
    
      return (
        <form onSubmit={handleSubmit}>
          <input type="text" value={value} onChange={handleChange} />
          <button type="submit">Submit</button>
        </form>
      );
    };
    

    11. Context API

    Use the Context API for state management across the component tree.

    import { createContext, useContext } from 'react';
    
    const MyContext = createContext();
    
    const MyProvider = ({ children }) => {
      const value = 'Hello from context';
    
      return (
        <MyContext.Provider value={value}>
          {children}
        </MyContext.Provider>
      );
    };
    
    const MyComponent = () => {
      const contextValue = useContext(MyContext);
    
      return <div>{contextValue}</div>;
    };
    

    12. Custom Hooks

    Create reusable logic with custom hooks.

    import { useState, useEffect } from 'react';
    
    const useFetch = (url) => {
      const [data, setData] = useState(null);
    
      useEffect(() => {
        fetch(url)
          .then(response => response.json())
          .then(data => setData(data));
      }, [url]);
    
      return data;
    };
    
    // Usage
    const DataComponent = () => {
      const data = useFetch('/api/data');
    
      return <div>{data ? JSON.stringify(data) : 'Loading...'}</div>;
    };
    

    13. Memoization with useMemo

    Optimize performance by memoizing expensive calculations.

    import { useMemo } from 'react';
    
    const ExpensiveComponent = ({ number }) => {
      const expensiveCalculation = useMemo(() => {
        // Assume this is a computationally expensive operation
        return number * 2;
      }, [number]);
    
      return <div>{expensiveCalculation}</div>;
    };
    

    14. useCallback

    Use useCallback to memoize functions to prevent unnecessary re-renders.

    import { useCallback } from 'react';
    
    const Button = ({ onClick }) => {
      return <button onClick={onClick}>Click me</button>;
    };
    
    const ParentComponent = () => {
      const handleClick = useCallback(() => {
        console.log('Button clicked');
      }, []);
    
      return <Button onClick={handleClick} />;
    };
    

    15. useReducer

    Manage complex state logic with the useReducer Hook.

    import { useReducer } from 'react';
    
    const reducer = (state, action) => {
      switch (action.type) {
        case 'increment':
          return { count: state.count + 1 };
        case 'decrement':
          return { count: state.count - 1 };
        default:
          throw new Error();
      }
    };
    
    const Counter = () => {
      const [state, dispatch] = useReducer(reducer, { count: 0 });
    
      return (
        <div>
          <p>Count: {state.count}</p>
          <button onClick={() => dispatch({ type: 'increment' })}>Increment</button>
          <button onClick={() => dispatch({ type: 'decrement' })}>Decrement</button>
        </div>
      );
    };
    

    16. Fragments

    Use fragments to group multiple elements without adding extra nodes to the DOM.

    const MyComponent = () => {
      return (
        <>
          <h1>Title</h1>
          <p>Description</p>
        </>
      );
    };
    

    17. Portals

    Render children into a DOM node outside the parent component’s DOM hierarchy.

    import { createPortal } from 'react-dom';
    
    const Modal = ({ children }) => {
      return createPortal(
        <div className="modal">
          {children}
        </div>,
        document.getElementById('modal-root')
      );
    };
    

    18. Error Boundaries with Error Boundary Component

    Use class components for error boundaries.

    import { Component } from 'react';
    
    class ErrorBoundary extends Component {
      constructor(props) {
        super(props);
        this.state = { hasError: false };
      }
    
      static getDerivedStateFromError(error) {
        return { hasError: true };
      }
    
      componentDidCatch(error, errorInfo) {
        console.log(error, errorInfo);
      }
    
      render() {
        if (this.state.hasError) {
          return <h1>Something went wrong.</h1>;
        }
    
        return this.props.children;
      }
    }
    
    // Usage
    <ErrorBoundary>
      <MyComponent />
    </ErrorBoundary>
    

    19. Lazy Loading with React.lazy and Suspense

    Dynamically import components to reduce the initial load time.

    import { lazy, Suspense } from 'react';
    
    const LazyComponent = lazy(() => import('./LazyComponent'));
    
    const App = () => {
      return (
        <Suspense fallback={<div>Loading...</div>}>
          <LazyComponent />
        </Suspense>
      );
    };
    

    20. PropTypes for Type Checking

    Use prop-types to document and enforce component prop types.

    import PropTypes from 'prop-types';
    
    const Greeting = ({ name }) => {
      return <h1>Hello, {name}!</h1>;
    };
    
    Greeting.propTypes = {
      name: PropTypes.string.isRequired,
    };
    

    Functional components offer a clean and straightforward way to build React applications, especially with the powerful capabilities introduced by Hooks. This cheat sheet provides a quick reference to essential concepts, helping you write effective and efficient React code.

  • Nuxt Cheat Sheet & Nuxt.js Essentials

    In this article, we will look into some of the Nuxt Cheat Sheet and Nuxt.js Essentials and how we can use them in our application. It’s advisable to understand the basics of Vuejs before moving to NuxtJs. Before we start with our Nuxt Cheat Sheet, let’s learn about Nuxt.

    Nuxt.js is a free and open-source web application framework based on Vue.js, Node.js, Webpack, and Babel.js. The framework is advertised as a “meta-framework for universal applications”

    Let’s look at some of the essentials in Nuxt:

    Nuxt Cheat Sheet

    nuxt cheat sheet

    Installation of Nuxt Js

    You can set up a new Nuxt project by using the Nuxt toolkit or by setting it up from scratch.

    • Setting up using the Nuxt toolkit:
        npx create-nuxt-app <name of project>
        cd <name of project>
        npm install #installs the project default dependencies
        npm run dev # serves the application on a local port
    • Setting up from scratch:
            Create a `package.json` file and add this code:
        {
        "name": "stater app",
        "scripts": {
          "dev": "nuxt"
        }
        }

    After doing this, run npm install --save nuxt to store the Nuxt dependency and then run npm run dev to serve the application.

    Nuxt Directory Structure

    • Assets: This folder contains uncompiled assets and files like Sass and less
    • Static : This directory contains unchanged files like pictures and text files
    • Components: This is where we store all our reusable components.
    • layout : Nuxt also comes with the ability to create multiple layouts for an application
    • Middlewares : This is where we write functions that will run before a page is loaded
    • Pages : This directory is used by Nuxt for routing.
    • Plugins : This is where we configure all our JS plugins such as Sweetheart, Carousel
    • Store : All Vuex files are kept here for state management.

    Nuxt Components

    • Routing: Just like using router-link Vuejs for routing, we can also use nuxt-link it is for routing in a nuxtjs application. We can also route to dynamic routes:
        <nuxt-link :to="'/cats' + cat.id">Get Cat By Id</nuxt-link>
    • Nuxt-child: This is used to display the child component route in a nested route:
        <template>
          <div>
            <h1>I am the parent view</h1>
            <nuxt-child />
          </div>
        </template>;
    • Error Pages: Nuxt gives the ability to create custom error pages for displaying errors in a better format. You can get to display errors based on their error codes and error messages. To create this page, create an error.vue page inside the pages directory and store these codes:
        <template>
         <h1 v-if="error.statusCode === 500">
         Something Went wrong
         </h1>
         <h1 v-else>An error occurred</h1>
         <nuxt-link to="/">Home page</nuxt-link>
        </template>
        <script>
        export default {
         props: ['error'],
         layout: 'error'
        }
        </script>
    • Layouts: You can define custom layouts for different pages. It’s as easy as creating a simple Vuejs component:
        <template>
          <div class="container">
            <nuxt />
          </div>
        </template>
    • Vuex Store: We also can use the Vuex store in our component for state management. Nuxt also automatically adds Vuex to your project components, meaning that we don’t have to import them. We can use them in this manner :
        <template>
         <button @click="$store.commit('increment')">
         {{ $store.state.counter }}
         </button>
        </template>

    The Nuxt Config File

    Nuxt comes with a config file. It is pre-populated based on the config when creating a new Nuxt project using the Nuxt toolkit. This is a sample format of a nuxt.config.js file:

        export default {
            css: [
                'bulma/css/bulma.css',
                '~/css/main.css'
            ],
            generate: {
                routes: function () {
                    return [
                        '/users/1',
                        '/users/2',
                        '/users/3'
                    ];
                }
            },
            loading: '~/components/loading.vue',
            head: {
                meta: [{
                        charset: 'utf-8'
                    },
                    {
                        name: 'viewport',
                        content: 'width=device-width, initial-scale=1'
                    }
                ],
                link: [{
                    rel: 'stylesheet',
                    href: 'https://font.com',
                }]
            },
            plugins: ['~/plugins/vue-notifications']
        }

    This config helps us configure our application files such as plugins, HTML head elements, style sheets, javascript CDN, etc.

    Nuxt Deployment Methods

    Nuxt.js lets us choose between three modes to deploy our application:

    • Universal,
    • Static Generated
    • SPA(single page application).

    SPA

    This mode organizes our project using convention over configuration folder structure and config files. To use this mode, change the mode in the nuxt.config file to spa.

    Static

    This mode lets pages get pre-rendered into HTML and has a high SEO and page load score. The content is generated at build time.

    Universal

    This mode executes your JavaScript on both the client and the server it is also known as SSR(server-side rendering). All routes have high SEO and page load scores. Dynamically get routes rendered on the server before being sent to the client.

    If you are looking for NuxtJs Admin Dashboard Template then you can check out below useful Admin Template which can save you time, money, and energy:

    Modernize Free NuxtJs Admin Dashboard Template

    Conclusion

    Thus we have learned and seen Nuxt Cheat Sheet and Nuxt.js Essentials. This will be very helpful as a web developer for your current or upcoming project. If you are looking for a Cheat Sheet for other frameworks, then you can find related articles below.

    Next.js Cheat sheet: Ultimate Guide to Nextjs

    The Ultimate React Cheat Sheet

    Angular Cheat Sheet

    The Ultimate Vue Cheat Sheet


  • The Ultimate Vue Cheat Sheet

    The Ultimate Vue Cheat Sheet

    Vuejs has become one of the most successfully applied, loved, and trusted frontend JavaScript frameworks in our community. The Vue3 comes with a whole lot of new features. In this article, we will go through all the fundamentals of Vue2 and Vue3. A Vue Cheat Sheet to make your life easier.

    vue cheat sheet

    Vue Cheat Sheet for Version 3 and Version 2

    We will break down our Vue cheat sheet into different sections like global APIs, Vue Configs, and the rest.

    Vue DOM

    • new Vue({}): This method provides the Vuejs instance with an existing DOM element to mount on. This is where all your Vuejs Codes are defined
    • el: A CSS selector string or an actual HTMLElement that all the Vuejs codes will be mounted.
    • template: A string template that is used as the markup for the Vue instance. Your Vuejs components are defined here.
    • render: h => h(App): The render function receives a createElement method as it is the first argument used to create VNodes. Aliasing createElement to h is a common convention you’ll see in the Vue ecosystem and is required for JSX. If h is not available in the scope, your app will throw an error.
    • renderError (createElement, err): This provides render output when the default render function encounters an error. The error encounter will be passed into the function as a second parameter.

    Vue Data Property

    • props: This is a list of attributes that are exposed to accept data from their parent component. You can implement this using an array and then pass all the parent data into it. It also accepts extra configs for data type checking and custom validation.
        props:['users','samples']
    • data(){return{}}: This is a data object for a particular Vuejs instance. Here Vuejs converts its properties into getter/setters to make it “reactive”.
        data() {
          return {
            name:"Sunil",
            age:80
        }
        }
    • computed: Computed properties calculate a value rather than store a value. These computed properties are cached and only re-computed on reactive dependency changes.
        computed:{
          sumNumbers:function() {
            return this.a * 2
         }
        }
    • watch: This is an object where keys are expressions to watch and values are the corresponding callbacks. It listens when your data property has been changed.
        watch:{
          name:function(val,oldVal) {
           console.log('newval',val,'old',oldVal)
        } 
        }
    • methods: These are methods to be mixed into the Vue instance. This method can be accessed directly on the VM instance using the this keyword. Always avoid using arrow functions to define methods.
        methods:{
          logName() {console.log(this.name)}
        }

    Vue Lifecycle Hooks

    A component in Vuejs has a lifecycle that is managed by Vue itself when it creates the component, mounts the component to the DOM, updates the component, and destroys the components.

    • beforeCreate: This is called synchronously immediately after the instance has been initialized, before data observation and event/watcher setup.
        beforeCreated(){console.log('Before Created')}
    • created: This is called after the Vue instance is created. it is called synchronously immediately after the instance has been initialized, before data observation and event/watcher setup.
    • beforeMount: In this phase, it checks if any template is available in the object to be rendered in the DOM. If no template is found, then it considers the outer HTML of the defined element as a template.
    • mounted: This is called after the instance has been mounted, where el is replaced by the newly created vm.$el. If the root instance is mounted to an in-document element, vm.$el will also be in-document when mounted is called. If you want to wait until all the views are rendered, you can use the nextTick method inside the hook: this.$nextTick()
    • beforeUpdate: This gets fired before the changes reflect the original DOM element. Also, take note that the hook is not called during server-side rendering.
    • updated: The component’s DOM will have been updated when this hook is called, so you can perform DOM-dependent operations here. However, in most cases, you should avoid changing the state inside the hook. To react to state changes, it’s usually better to use a computed property or watcher instead.
    • beforeDestroy: This is called before the Vue instance is destroyed.
    • destroyed: This is called after the Vue instance has been destroyed.

    Vue 3 Lifecycle Hooks

    Vue 3 also comes with its life cycle hooks which are great for development. To use them we will have to import them into our components like this:

        import { onMounted, onUpdated, onUnmounted } from 'vue'
    Here we get to only import the hooks that we want to use. Here are the Vue 3 life cycle hooks:
    • onBeforeMount : This hook gets called before mounting occurs
    • onMounted : Once the component is mounted this hook is called
    • onBeforeUpdate: Called once a reactive data changes and before it re-rendered.
    • onUpdated : Called after re-rendering the component.
    • onBeforeUnmount: This is called before the Vue instance is destroyed
    • onUnmounted : This is called immediately after the Vue Instance is destroyed.
    • onActivated: Components in Vuejs can be kept alive, this hook is called when this component is activated.
    • onDeactivated: This is called once a kept-alive component is deactivated.
    • onErrorCaptured : This is great for error handling. This hook is called once an error is captured in a child component.

    Vue 3 Composition API

    Before we can access the Vue3 composition API we have to, first of all, install it:

        npm install @vue/composition-api

    After the installation was successful we can now import it into our main.js file:

        import Vue from 'vue';
        import CompositionApi from '@vue/composition-api';
        Vue.use(CompositionApi);

    With this done we are set to use the Vuejs Composition API in our application.

    Now let’s look at some of the Vue 3 features:

    • **setup()**: This function is called when an instance of a component has been created. This method takes in two parameters props and context. – Props are reactive values and can be watched:
        export default {
          props: {
            age: String,
          },
          setup(props) {
            watch(() => {
              console.log(`Sunil is : ` + props.age + "years old");
            });
          },
        };
    • The context here has this property attrs, slots, emit, parent, root. Always remember that this keyword is not available in the setup function meaning that this won’t work :
        setup() {
          function onClick() {
            this.$emit // not available
          }
        }
    • refs : The new way of getting a reference to an element or component instance in a template is by using the ref method. To use this, we have to first of all import it into our application like this:
        import { ref } from '@vue/composition-api'

    And then use it like this in our component:

        <template>
          <div>{{ count }}</div>
        </template>
        <script>
        import { ref } from '@vue/composition-api'
          export default {
            setup() {
              return {
                count: ref(0)
              }
            }
          }
        </script>

    Vue Global Configs

    The Vue.config the object is where we can define all our Vuejs global configs. One of the important parts of the Vue Cheat Sheet.

    • Vue.config.silent: This config disables all Vuejs logs and warnings
    • Vue.config.devtools: This adds configuration on whether to allow vue-devtools inspection or not
    • Vue.config.performance : This config enables component initializing, compiling, rendering, and patch performance tracing in the browser devtool timeline.
    • Vue.config.productionTip: This enables production tips on Vue startup.
    • Vue.config.ignoredElements: Make Vue ignore custom elements defined outside of Vue (e.g., using the Web Components APIs). Otherwise, it will throw a warning about an Unknown custom element.
    • Vue.config.errorHandler : This config assigns a handler for uncaught errors during component render function and watchers.
    • Vue.config.optionMergeStrategies : This defines custom merging strategies for options. This merge strategy receives the value of that option defined on the parent and child instances as the first and second arguments, respectively.

    Vue Templates and Themes

    If you are looking for VueJs Admin Dashboard Template then you can check out below useful Admin Template which can save you time, money, and energy:

    Modernize Free Vuetify + Vue js Admin Dashboard

    As the above Vue cheat sheet helps you to speed up your workflow, there is another great thing called ready-to-use Vue templates, which are more than helpful, They help you create visually stunning applications using ready-to-use design components provided in the template package. You can check them out for your application. You can download free vue templates as well if you do not want to invest to start with. Hope you enjoyed this Vue Cheat Sheet, we also have other articles regarding Cheat Sheets as below:

    Other Cheat Sheets:

    The Ultimate React Cheat Sheet

    Next.js Cheat sheet: Ultimate Guide to Nextjs

    Angular Cheat Sheet

    Nuxt Js Cheat Sheet | Nuxt.js Essentials

    The Ultimate Bootstrap Cheat Sheet: The Master List of Bootstrap Resources