Description (React)

React is the library for web and native user interfaces. Build user interfaces out of individual pieces called components written in JavaScript.
You must have basic knowledge in following steps
  • We must have basic knowledge about Node, NPM, JSX, style, Javascript, ES6, JSON Object, Array and etc
  • We must have basic knowledge about API
We will learn following topics
  • How to create components
  • How to use state and props
  • How to display data from API
  • How to use bootstrap
  • How to use sass style
  • How to pass data from one component to another
  • How to use hooks
  • How to use context api
  • How to use redux
  • How to use typescript in react
  • How to handle API in react
  • How to share data between components
  • How to create methods to generate components automatically
  • Many more lessions

Project Setup

How to create setup for react project
  • Install nodejs latest version
  • Install react cli globally in your system
  • Install npm
  • Create Project in JavaScript Template
    • Run Command: npx create-react-app my-app
  • Create Project using Vite
    • Run Command: npm create vite@latest my-app -- --template react-ts
    • Vite: to create project click on link Go to Vite

What is a semantic element in React

Semantic Elements:
A semantic element clearly describes its meaning to both the browser and the developer.
                  
                   <form>,<table>, and <article> - clearly defines its contents.
                   <footer>,<header>,<nav>,<section>,<time>
                  
                
Non-semantic elements:
                  
                   <div> and<span> - Tells nothing about its contents.
                  
                

Pseudo Class

Pseudo Class
A pseudo class is used to define a special state of an element, such as mouse over.
                  
                    // Example
                    a:hover, a:active, a:link
                  
                

Position in CSS

Position in CSS
The position property is used for the types of positioning methods for an element.
  • static - default
  • relative
  • fixed
  • absolute & sticky

What is Overflow in CSS?

Overflow in CSS
The overflow property controls if the content that is too big to fit into an area:
  • visible - default, the overflow is not clipped
  • hidden - The overflow is clipped
  • scroll - The overflow is clipped, scrollbar added
  • auto - Similar to scroll, it adds scrollbar only when necessary

Z Index

Z Index
The Z-index property move the order of an element. When elements are positioned, they can overlap other elements -> in front or behind.

Inline-block

Inline-block
Compared to display-inline thethe major difference is that display inline block allows to set a width and height on the element with the top/bottom margins/padding.

Float & Clear in CSS

Float in CSS
The float property specifies how an element should float for positioning -> left, right, none, inherit.
Clear in CSS
If we want the next element below, we will have to use the clear property: none, left, right, both, inherit.

Box Modal in CSS

Box Modal in css
All html elements can be considered as boxes. The box model is used to define about design & layout; boxes consist of padding, border, and margins.

!Important in CSS

!Important in CSS
The important rule in CSS is used to add more importance to a property/value than normal.

Selectors in CSS

Selectors in CSS
CSS selectors are used to find or select the HTML elements you want to style.
  • Simple selectors (name, id, class)
  • Combinator selectors (the relationship between elements: descendant (space), child (>), sibling (+)
  • adjacent sibling (~))
  • Pseudo-class selectors (:hover)
  • Pseudo-elements selectors (p::first-line, ::first-letter)
  • Attribute selectors ([title="robot"])

Math Function in CSS

Math Function in CSS
These are math function in css
                  
                  #div1 {
                      width: max(50%, 300px);
                  }
                  #div2 {
                      width: min(50%, 300px);
                  }
                  #div3 {
                      width: calc(100% - 120px);
                  }

                  
                

What is units in CSS?

Units in CSS?
Units are used to define the length in CSS. Absolute length and Relative length
  • px (pixels)
  • em (relative to font-size of the element)
  • rem (relative to font-size of the root element)
  • ex (relative to x-height of the element)
  • ch (relative to width of the "0" character)
  • vw (relative to 1% of the width of the viewport)
  • vh (relative to 1% of the height of the viewport)
  • vmin/vmax (relative to 1% of the viewport's smaller/larger dimension)

What is Flexbox?

Flex Box
Flexbox is a one-dimensional layout method for arranging items in rows or columns. Items flex or expand to fill additional space or shrink to fit into smaller spaces.
                  
                     <div class="container">
                       <div class="box">1</div>
                       <div class="box">2</div>
                       <div class="box">3</div>
                       <div class="box">2</div>
                     </div>
                  
                
                  // CSS:
                  
                     .container {
                        display: flex;
                        justify-content: space-between; /* Distributes the items with space between them */
                        align-items: center;            /* Centers the items vertically */
                        height: 100vh;                  /* Full height of the viewport */
                        padding: 20px;
                        background-color: #f4f4f4;
                      }

                      .box {
                        background-color: #4CAF50;
                        color: white;
                        padding: 20px;
                        text-align: center;
                        flex: 1;                        /* Each box takes equal space */
                        margin: 10px;
                      }
                  
                

Controlled & Uncontrolled Components

Uncontrolled Components
Uncontrolled components are those elements that are handled by the DOM but are not under the control of React state.
                  
                    <input /> or <textarea />
                  
                
Controlled components
Controlled components in React are those where the state of the component manages the form's data. It uses props to get its current value and callbacks like onChange, onClick, etc., to make changes. The control of the component is under React state.

Reducer vs useReducer

Reducer
A reducer is a function that defines how the state gets updated based on an action type.
                  
                    export const reducer = (state: State, action: Action) => {
                      switch (action.type) {
                        case 'FETCH_REQUEST':
                          return { ...state, loading: true };
                        case 'FETCH_SUCCESS':
                          return { ...state, products: action.payload, loading: false };
                        case 'FETCH_FAIL':
                          return { ...state, loading: false, error: action.payload };
                        default:
                          return state;
                      }
                    };
                  
                
useReducer
useReducer is a react hook that allows us to add a reducer to our component. It is similar to the concept of reducers in Redux.
                  
                    import {useReducer} from 'react';
                    const [state, dispatch] = React.useReducer(reducer, appInitialState);
                  
                

SASS and SCSS

SASS and SCSS
  • SASS stands for Syntactically Awesome Style Sheets.
  • SASS is an extension of CSS.
  • SASS is a CSS pre-processor.
  • SASS is completely compatible with all versions of CSS.
  • SASS reduces the repetition of CSS.
  • SASS and SCSS can import each other.
  • SASS actually makes CSS more powerful with math and variable support.
  • SASS extension: .sass, .scss → .scss
                          
                            // style.scss  file name
                            $bgColor: blue;
                            $textColor: red;
    
                            body {
                              background-color: $bgColor;
                              color: $textColor;
                            }
                          
                        
  • SASS → Syntactically Awesome Stylesheet
  • SCSS → Sassy Cascading Stylesheet

What is lazy loading?

Lazy Loading
Lazy loading in React allows us to split our code into smaller chunks, loading only the code that is needed for a particular part of our application.
Lazy loading is used to dynamically import components only when they are needed.
"Suspense" is a component provided by React that lets you "wait" for the dynamic import to load, showing a fallback UI in the meantime.
                  
                   //Example (in this case a simple "loading..." message):
                    <React.Suspense fallback={<div>Loading...</div>}>
                       <Products />
                    </React.Suspense>
                  
                

Use Strict Mode

Use Strict Mode
  1. The 'use strict' directive is new in ECMAScript 5.
  2. The purpose of 'use strict' is to indicate that the code should be executed in Strict Mode.
  3. Variables must be declared before they are used.
  4. Deleting a variable or function is not allowed.
  5. Assigning a value to an undeclared variable is not allowed.
Example
                  
                    "use strict";
                    x = 10;
                    console.log(x);  // This will give an error because x is not declared
                    function sum(a, b) {
                      return a + b;
                    }
                    delete sum;  // This will give an error in strict mode
                  
                

Constructor

Constructor
The constructor is a method used to initialize an object's state in a class. It is automatically called during the creation of an object in a class.
                  
                    import React from 'react';
                    class HomeComponent extends React.Component {
                      constructor (props) { // constructor
                          super(props);
                          this.state = { // state declaration and initialization
                            city: 'Mumbai';
                          };
                        }
                      render () {
                        return (
                          <div>
                            <p> This is class component {this.props.name} </p>
                          </div>
                        );
                      }
                    }
                    export default HomeComponent;
                  
                

Super

Super
Super function is to call the constructor of the parent class. It is used when we need to access a few variables.
                  
                      constructor (props) { 
                          super(props);  // super function
                          this.state = { 
                            city: 'Mumbai';
                          };
                        }
                  
                

Error Boundries

Error Boundries
A JavaScript error in a part of the UI should not crash the whole application. To solve this problem for React users, React 16 introduces the new concept of an error boundary.
Error boundaries are React components that catch JavaScript errors anywhere in their child component tree, log those errors, and display a fallback UI instead of the component tree that crashed.
Error boundaries catch errors during rendering, in lifecycle methods, and in constructors of the whole tree below them.
Error boundaries do not catch errors for:
  • Event handlers
  • Asynchronous code
  • Server-side rendering
  • Errors thrown in the boundary itself
                  
                    constructor(props) {
                        super(props);
                        this.state = { hasError: false };
                    }

                    static getDerivedStateFromError(error) {
                      return { hasError: true };
                    }

                    componentDidCatch(error, info) {
                      console.log(error);
                    }
                  
                

Authorization vs Authentication

Authorization
The authorization is a process utilized in an app that helps in controlling the informational access and limiting actions performed by users.
Authentication
Authentication is a process to check if the user is allowed to access the information or perform any action. If an authenticated user is using the app, they have identified their true identity through several ways, such as providing credentials. Authentication ways:
  • Cookie-based authentication
  • OpenID
  • Token-based authentication
  • hird-party access (OAuth, API-token)
  • SAML
  • Token-based Authentication:
  • hird-party access (OAuth, API-token)
Token-based Authentication:
There are base64 encoded strings that include the header, payload, and signature.

Higher Order Component

Higher-Order-Component (HOC)
  • HOC is an advanced technique in React for reusing component logic.
  • Conceptually, a higher-order-component is a function that takes a component and returns a new component.
  • Used to compose components for code reuse.
  • HOC is a pure function. That means it has no side effects. It only returns a new component.
                  
                    export const HocExample = () => {
                      return (
                        <View>
                          <HOCRed cmp={Counter3} />
                          <HOCBlue cmp={Counter3} />
                        </View>
                      );
                    };

                    const HOCRed = (props) => {
                      return (
                        <View style={{ background: "red" }}>
                          <props.cmp />
                        </View>
                      );
                    };

                    const HOCBlue = (props) => {
                      return (
                        <View style={{ background: "blue" }}>
                          <props.cmp />
                        </View>
                      );
                    };
                  
                

How to create custome hooks

Custom Hook
                  
                  // Custom hooks are readable
                  // Custom hooks are maintainable
                  // Custom hooks are reusable
                  import { useEffect, useState } from "react";
                  const useFetch = (url) => {
                    const [data, setData] = useState(null);
                    const [isLoading, setLoading] = useState(true);
                    const [error, setError] = useState(null);

                    useEffect(() => {
                      fetch(url)
                        .then((res) => res.json())
                        .then((json) => setData(json))
                        .catch((error) => setError(error))
                        .finally(() => setLoading(false));
                    }, [url]);

                    return [data, error, isLoading];
                  };
                  
                
Use of Custom Hook:
                    
                      import useFetch from "./useFetch";
                      const url = "https://jsonplaceholder.typicode.com/posts";
                      const [data, error, isLoading] = useFetch(url);
                    
                  

Pure Component

Pure Component
A React component is considered pure if it renders the same output for the same state and props. It prevents unwanted re-rendering.
                  
                    import { PureComponent } from 'react';
                    class Profile extends PureComponent {
                      render() {
                        return 

Hello, {this.props.name}!

; } }

Hot and Live Reloading

Hot Reloading
Only refresh the files that were changed without losing the state of the app.
Live Reloading
Reloads or refreshes the entire app when a file changes. Live reloading would restart the app and load the app back to the initial route.

Difference between 2 dates

Difference between two dates
How to get difference between two date?
                  
                    const date1 = new Date(2021-04-10);
                    const date2 = new Date(2021-04-26);

                    const diffTime = Math.abs(date2 - date1);
                    const diffDays = Math.ceil(diffTime / (1000 * 60 * 60 * 24));
                  console.log(diffDays);
                  
                

Performance Optimization

Performance Optimization
  • Keep component state local where necessary
  • Memoizing React components to prevent unnecessary re-renders
  • Implementing React.memo() is a HOC
  • Using the useCallback and useMemo() hooks with array dependencies
  • Code splitting in React using dynamic imports
                      
                         import Home from "./components/Home";
                         const Home = React.lazy(() => import("./components/Home"));
                      
                    
    To use chunks on demand
  • Using immutable data structures

What is Pseudo-element?

What is Pseudo-element?
A pseudo-element is used to style a specific part of an element.
  • Style the ::first-line of an element
  • Style the ::first-letter
                        
                            p::first-line {
                                /* styles */
                            }