ESLint + Prettier + Node (Express) + Typescript

Configure Typescript

1. Install Dev Dependencies

npm i -D eslint-config-standard-with-typescript@latest @typescript-eslint/eslint-plugin eslint eslint-plugin-import eslint-plugin-n eslint-plugin-promise typescript eslint-plugin-node eslint-config-node
npm i -D prettier eslint-plugin-prettier eslint-config-prettier 
npm i -D nodemon jest supertest ts-jest ts-node @types/cors @types/express @types/jest @types/supertest

2. Create a .eslintrc.json file in your root folder

{
  "env": {
    "browser": true,
    "es2021": true,
    "node": true
  },
  "extends": [
    "standard-with-typescript",
    "plugin:node/recommended",
    "plugin:prettier/recommended",
    "prettier"
  ],
  "overrides": [],
  "parser": "@typescript-eslint/parser",
  "parserOptions": {
    "ecmaVersion": "latest",
    "sourceType": "module",
    "project": "./tsconfig.json"
  },
  "plugins": [
    "@typescript-eslint",
    "prettier"
  ],
  "rules": {
    "@typescript-eslint/no-var-requires": "off",
    "@typescript-eslint/no-misused-promises": "off",
    "@typescript-eslint/explicit-function-return-type": "off",
    "@typescript-eslint/prefer-nullish-coalescing": "off",
    "@typescript-eslint/strict-boolean-expressions": "off",
    "node/no-unsupported-features/es-syntax": "off",
    "node/no-unpublished-import": "off",
    "node/no-missing-import": "off",
    "node/no-missing-require": "off",
    "arrow-body-style": "off",
    "prefer-arrow-callback": "off",
    "array-callback-return": "off"
  }
}

Create .prettierrc.json

{
  "arrowParens": "always",
  "trailingComma": "es5",
  "singleQuote": false,
  "tabWidth": 2,
  "printWidth": 100,
  "semi": true,
  "endOfLine": "auto"
}

.prettierignore to let Prettier know what files/folders not to format

build

3. In the settings.json file

{
  // config related to code formatting
  "editor.defaultFormatter": "esbenp.prettier-vscode",
  "editor.formatOnSave": true,
  "[javascript]": {
    "editor.formatOnSave": false,
    "editor.defaultFormatter": null
  },
  "[javascriptreact]": {
    "editor.formatOnSave": false,
    "editor.defaultFormatter": null
  },
  "javascript.validate.enable": false,
  "editor.codeActionsOnSave": {
    "source.fixAll.eslint": true,
    "source.fixAll.tslint": true,
    "source.organizeImports": false
  },
  "eslint.alwaysShowStatus": true,
  // emmet
  "emmet.triggerExpansionOnTab": true,
  "emmet.includeLanguages": {
    "javascript": "javascriptreact"
  }
}

4. Finally, we have to add the scripts in the package.json

"scripts": {
   "start": "nodemon",
   "build": "tsc",
   "test": "jest",
   "test:watch": "jest --watchAll",
   "lint": "eslint src/**/*.{js,ts}",
   "lint:fix": "eslint --fix src/**/*.{js,ts}",
   "format": "prettier --check **/*.{js,ts}",
   "format:fix": "prettier --write src/**/*.{js,ts}"
},

ESLint + Prettier + Node (Express)

1. Install Dev Dependencies

npm i -D eslint eslint-config-airbnb-base eslint-plugin-node eslint-config-node
npm i -D prettier eslint-plugin-prettier eslint-config-prettier 

2. Create a .eslintrc.json file in your root folder

{
  "env": {
    "browser": true,
    "es2021": true,
    "node": true
  },
  "extends": [
    "airbnb-base",
    "plugin:node/recommended",
    "plugin:prettier/recommended",
    "prettier"
  ],
  "overrides": [],
  "parserOptions": {
    "ecmaVersion": "latest",
    "sourceType": "module"
  },
  "plugins": [
    // "jest",
    // "security",
    "prettier"
  ],
  "rules": {
    "import/no-extraneous-dependencies": "off",
    "node/no-unsupported-features/es-syntax": "off",
    "no-console": "off",
    "func-names": "off",
    "no-underscore-dangle": "off",
    "consistent-return": "off",
    "jest/expect-expect": "off",
    "security/detect-object-injection": "off",
    "no-unused-vars": "off",
    "node/no-unpublished-require": "off",
    "no-undef": "off",
    "no-return-await": "off",
    "arrow-body-style": "off",
    "prefer-arrow-callback": "off",
    "array-callback-return": "off"
  }
}

Create .prettierrc.json

{
  "arrowParens": "always",
  "trailingComma": "es5",
  "tabWidth": 2,
  "singleQuote": false,
  "printWidth": 125,
  "semi": true,
  "endOfLine": "auto"
}

.prettierignore to let Prettier know what files/folders not to format

build

3. In the settings.json file

{
  // config related to code formatting
  "editor.defaultFormatter": "esbenp.prettier-vscode",
  "editor.formatOnSave": true,
  "[javascript]": {
    "editor.formatOnSave": false,
    "editor.defaultFormatter": null
  },
  "[javascriptreact]": {
    "editor.formatOnSave": false,
    "editor.defaultFormatter": null
  },
  "javascript.validate.enable": false,
  "editor.codeActionsOnSave": {
    "source.fixAll.eslint": true,
    "source.fixAll.tslint": true,
    "source.organizeImports": false
  },
  "eslint.alwaysShowStatus": true,
  // emmet
  "emmet.triggerExpansionOnTab": true,
  "emmet.includeLanguages": {
    "javascript": "javascriptreact"
  }
}

4. Finally, we have to add the scripts in the package.json

  "scripts": {
    "test": "jest",
    "test:watch": "jest --watchAll",
    "lint": "eslint src/**/*.{js,ts}",
    "lint:fix": "eslint --fix src/**/*.{js,ts}",
    "format": "prettier --check **/*.{js,ts}",
    "format:fix": "prettier --write src/**/*.{js,ts}"
  },

React Snippets

Email Validation

const [email, setEmail] = useState(null);

/* Email validation */
const emailValidation = () => {
    const regex =
        /^(([^<>()[\]\.,;:\s@\"]+(\.[^<>()[\]\.,;:\s@\"]+)*)|(\".+\"))@(([^<>()[\]\.,;:\s@\"]+\.)+[^<>()[\]\.,;:\s@\"]{2,})$/i;
    return !(regex.test(email) === false);
};

const isEmailValid = emailValidation();

JSX

return (
     <div className="form-button-area">
        <Button type="submit" disabled={email && isEmailValid ? '' : 'disabled'}>
            {email && isEmailValid ? <Link to="/phone">Continue</Link> : 'Continue'}
        </Button>
    </div>
)

Retrieving value from <select> with multiple option in React

const handleChange = (e) => {
    const value = Array.from(e.target.selectedOptions, (option) => option.value);
    setQuestionsData({ ...questionsData, options: value });
};

target.selectedOptions return an array of HTMLCollection

React Typescript Form Component

import { useState } from 'react';
import fetch from 'node-fetch';
import './Contact.css';

const Contact = () => {
    // Defined interface
    interface User {
        name: string;
        email: string;
        phone: string;
        message: string;
        budget: string;
    }

    // Defined state
    const [userData, setUserData] = useState<User>({
        name: '',
        email: '',
        phone: '',
        message: '',
        budget: '',
    });

    const [successMessage, setSuccessMessage] = useState('');
    const [loading, setLoading] = useState(false);

    // Onchange event handler
    const handleChange = (event: React.ChangeEvent<HTMLInputElement>): void => {
        setUserData({ ...userData, [event.target.name]: event.target.value });
    };

    // Form handler
    const formHandler = (e: any) => {
        e.preventDefault();
        passUserData(userData);
    };

    // Custom function
    const passUserData = async (data: User) => {
        try {
            setLoading(true);
            const response = await fetch(`https://softcent-website.herokuapp.com/api/contact`, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify(data),
            });

            const responseData = await response.json();
            setLoading(false);

            if (response.ok) {
                console.log(responseData.data);
                // Set Message
                setSuccessMessage('Your query has been submitted!');

                // Window scroll top
                window.scrollTo(0, 0);

                // Input field empty
                setUserData({
                    name: '',
                    email: '',
                    phone: '',
                    message: '',
                    budget: '',
                });
            } else {
                console.log('Error');
            }
        } catch (err) {
            console.log(err);
            setLoading(false);
        }
    };

    return (
        <div className="contact-section">
            <div className="container">                
                {loading && <h1>Loading...</h1>}

                {!loading && (
                    <form onSubmit={formHandler} className="contact-form">
                        {successMessage && <p className="successMsg">{successMessage}</p>}
                        <div>
                            <label htmlFor="Name">1. What's you name?*</label>
                            <input
                                onChange={handleChange}
                                type="text"
                                name="name"
                                value={userData.name}
                                placeholder="Type your name here"
                                required
                            />
                        </div>
                        <div>
                            <label htmlFor="Email">2. Email address</label>
                            <input
                                onChange={handleChange}
                                type="text"
                                name="email"
                                value={userData.email}
                                placeholder="Enter your email"
                                required
                            />
                        </div>
                        <div>
                            <label htmlFor="Phone">3. Phone Number</label>
                            <input
                                onChange={handleChange}
                                type="text"
                                name="phone"
                                value={userData.phone}
                                placeholder="Enter your phone number"
                                required
                            />
                        </div>
                        <div>
                            <label htmlFor="Message">4. How can we help you?(optional)</label>
                            <input
                                onChange={handleChange}
                                type="text"
                                name="message"
                                value={userData.message}
                                placeholder="Enter your phone number"
                            />
                        </div>
                        <div>
                            <label htmlFor="Budget">5. Choose a Budget (EUR/USD)</label>
                            <input
                                onChange={handleChange}
                                type="text"
                                name="budget"
                                value={userData.budget}
                                placeholder="Less then 5000"
                                required
                            />
                        </div>
                        <div>
                            <button type="submit" className="form-button">
                                Get a quote
                            </button>
                        </div>
                    </form>
                )}
            </div>
        </div>
    );
};

export default Contact;

CSS Snippets

Responsive Rules

/* Small devices (Phones) */
@media only screen and (max-width:767px) { }
 
/* Medium devices (tablets, 768px and up) */
@media only screen and (min-width: 768px) and (max-width:992px) { }
 
/* Large devices (desktops, 992px and up) */
@media only screen and (min-width: 992px) { }
 
/* X-Large devices (large desktops, 1200px and up) */
@media only screen and (min-width: 1200px) { }

Scroll bar color

:-webkit-scrollbar {
    width: 6px;
    padding: 0 5px;
    background: #1f1c1a;
}
  
::-webkit-scrollbar-thumb {
    background: #333290;
    -webkit-box-shadow: inset 0 0 6px rgba(0,0,0,0.5);
}

Background Gradient

background: -webkit-linear-gradient(0deg, #95D146 10%, #76af2b 90%); /* Chrome 10+, Saf5.1+ */
background:    -moz-linear-gradient(0deg, #95D146 10%, #76af2b 90%); /* FF3.6+ */
background:     -ms-linear-gradient(0deg, #95D146 10%, #76af2b 90%); /* IE10 */
background:      -o-linear-gradient(0deg, #95D146 10%, #76af2b 90%); /* Opera 11.10+ */
background:         linear-gradient(0deg, #95D146 10%, #76af2b 90%); /* W3C */

Specify a background color for every element that is the second child of its parent

td:nth-child(2) {
    background: #ff0000;
}

Word Wrap

p {word-wrap:break-word;}

Box shadow

.box-shadow: -15px 0 15px -15px inset;

Box shadow on the left and right side only

-moz-box-shadow:inset 5px 0 5px -5px #CCCCCC,inset -5px 0 5px -5px #CCCCCC;
-webkit-box-shadow:nset 5px 0 5px -5px #CCCCCC, inset -5px 0 5px -5px #CCCCCC;
box-shadow:inset 5px 0 5px -5px #CCCCCC,inset -5px 0 5px -5px #CCCCCC;

Only bottom shadow

-webkit-box-shadow: 0 8px 6px -6px #CCCCCC;
-moz-box-shadow: 0 8px 6px -6px #CCCCCC;
box-shadow: 0 8px 6px -6px #CCCCCC;

Outline

:focus-visible {
  outline: none !important;
}
 
a:-webkit-any-link:focus-visible {
  outline-offset: unset !important;
}
 
a:focus {
  outline: none !important;
}

ESLint + Prettier + Next JS

ESlint & Prettier Configuration Link

1. You need to install these plugins

  • ESLint
  • Prettier – Code formatter

npm init @eslint/config or npx eslint –init

2. Or Manually Install Dev Dependencies

yarn add eslint-plugin-react eslint-config-airbnb@latest eslint --dev
yarn add prettier eslint-config-prettier eslint-plugin-prettier --dev

3. Create a .eslintrc.json file in your root folder

{
  "env": {
    "browser": true,
    "es2021": true
  },
  "extends": [
    "airbnb",
    "eslint:recommended",
    "plugin:react/recommended",
    "plugin:@next/next/recommended",
    "prettier"
  ],
  "overrides": [],
  "parserOptions": {
    "ecmaVersion": "latest",
    "sourceType": "module"
  },
  "plugins": ["react", "prettier"],
  "rules": {
    "react/jsx-no-bind": "off",
    "jsx-a11y/click-events-have-key-events": "off",
    "jsx-a11y/no-static-element-interactions": "off",
    "arrow-body-style": "off",
    "no-underscore-dangle": "off",
    "no-unused-expressions": "off",
    "jsx-a11y/anchor-is-valid": "off",
    "jsx-a11y/anchor-has-content": "off",
    "no-unused-vars": "off",
    "react/function-component-definition": [
      "error",
      {
        "namedComponents": ["function-declaration", "arrow-function"]
      }
    ],
    "react/jsx-filename-extension": [
      1,
      {
        "extensions": [".js", ".jsx"]
      }
    ],
    "prettier/prettier": [
      "error",
      {
        "trailingComma": "all",
        "singleQuote": true,
        "printWidth": 100,
        "tabWidth": 4,
        "semi": true,
        "endOfLine": "auto",
        "jsxSingleQuote": true,
        "bracketSpacing": true
      }
    ],
    "react/react-in-jsx-scope": "off",
    "react/prop-types": "off",
    "react/jsx-props-no-spreading": "off"
  }
}

4. In the settings.json file

{
  // config related to code formatting
  "editor.defaultFormatter": "esbenp.prettier-vscode",
  "editor.formatOnSave": true,
  "[javascript]": {
    "editor.formatOnSave": false,
    "editor.defaultFormatter": null
  },
  "[javascriptreact]": {
    "editor.formatOnSave": false,
    "editor.defaultFormatter": null
  },
  "javascript.validate.enable": false,
  "editor.codeActionsOnSave": {
    "source.fixAll.eslint": true,
    "source.fixAll.tslint": true,
    "source.organizeImports": true
  },
  "eslint.alwaysShowStatus": true,
  // emmet
  "emmet.triggerExpansionOnTab": true,
  "emmet.includeLanguages": {
    "javascript": "javascriptreact"
  }
}

ESLint + Prettier + Typescript with React

1. Install Dev Dependencies Eslint & Prettier

yarn add -D eslint-plugin-react@latest @typescript-eslint/eslint-plugin@latest eslint @typescript-eslint/parser@latest eslint-plugin-import eslint-import-resolver-typescript eslint-config-airbnb-typescript
yarn add -D prettier eslint-config-prettier eslint-plugin-prettier

2. Create .eslintrc.json file in your root directory

{
  "env": {
    "browser": true,
    "es2021": true
  },
  "extends": [
    "airbnb-typescript",
    "eslint:recommended",
    "plugin:react/recommended",
    "plugin:import/recommended",
    "plugin:@typescript-eslint/recommended",
    "plugin:prettier/recommended",
    "prettier"
  ],
  "overrides": [],
  "parser": "@typescript-eslint/parser",
  "parserOptions": {
    "ecmaVersion": "latest",
    "sourceType": "module",
    "project": "./tsconfig.json"
  },
  "plugins": [
    "react",
    "@typescript-eslint",
    "prettier"
  ],
  "rules": {
    "no-undef": "off",
    // "@typescript-eslint/no-explicit-any": "error",
    "import/no-named-as-default-member": "off",
    "react/react-in-jsx-scope": "off",
    "arrow-body-style": "off",
    "prefer-arrow-callback": "off",
    "array-callback-return": "off",
    "react/function-component-definition": [
      "error",
      {
        "namedComponents": [
          "function-declaration",
          "arrow-function"
        ]
      }
    ],
    "react/jsx-filename-extension": [
      1,
      {
        "extensions": [
          ".js",
          ".jsx",
          ".tsx"
        ]
      }
    ]
  },
  "settings": {
    "import/resolver": {
      "typescript": {}
    },
    "react": {
      "version": "detect"
    }
  }
}

Create .prettierrc.json

{
  "arrowParens": "always",
  "trailingComma": "es5",
  "singleQuote": false,
  "tabWidth": 2,
  "printWidth": 100,
  "semi": true,
  "endOfLine": "auto"
}

.prettierignore to let Prettier know what files/folders not to format

build

3. In the settings.json file

{
  // config related to code formatting
  "editor.defaultFormatter": "esbenp.prettier-vscode",
  "editor.formatOnSave": true,
  "[javascript]": {
    "editor.formatOnSave": false,
    "editor.defaultFormatter": null
  },
  "[javascriptreact]": {
    "editor.formatOnSave": false,
    "editor.defaultFormatter": null
  },
  "javascript.validate.enable": false, //disable all built-in syntax checking
  "editor.codeActionsOnSave": {
    "source.fixAll.eslint": true,
    "source.fixAll.tslint": true,
    "source.organizeImports": false
  },
  "eslint.alwaysShowStatus": true,
  // emmet
  "emmet.triggerExpansionOnTab": true,
  "emmet.includeLanguages": {
    "javascript": "javascriptreact"
  }
}

4. Finally, we have to add the scripts in the package.json

  "scripts": {
    "lint": "eslint src/**/*.{js,jsx,ts,tsx}",
    "lint:fix": "eslint --fix src/**/*.{js,jsx,ts,tsx}",
    "format": "prettier --check **/*.{js,jsx,ts,tsx}",
    "format:fix": "prettier --write src/**/*.{js,jsx,ts,tsx,css}"
  },

ESLint + Prettier + React

Eslint & Prettier configuration:

https://github.com/learnwithsumit/think-in-a-react-way/tree/lesson-3

1. You need to install these plugins

  • ESLint
  • Prettier – Code formatter

npm init @eslint/config or npx eslint –init

Or Manually Install Dev Dependencies

yarn add -D eslint-plugin-react eslint-config-airbnb@latest eslint eslint-plugin-import eslint-plugin-react-hooks
yarn add -D prettier eslint-config-prettier eslint-plugin-prettier

2. Create a .eslintrc.json file in your root directory

{
  "env": {
    "browser": true,
    "es2021": true
  },
  "extends": [
    "airbnb",
    "eslint:recommended",
    "plugin:react/recommended",
    "plugin:prettier/recommended",
    "prettier"
  ],
  "overrides": [],
  "parserOptions": {
    "ecmaVersion": "latest",
    "sourceType": "module"
  },
  "plugins": [
    "react",
    "prettier"
  ],
  "rules": {
    "no-undef": "off",
    "no-unused-vars": "off",
    "react/jsx-no-target-blank": "off",
    "react/jsx-props-no-spreading": "off",
    "react/prop-types": "off",
    "react/react-in-jsx-scope": "off",
    "arrow-body-style": "off",
    "prefer-arrow-callback": "off",
    "array-callback-return": "off",
    "react/function-component-definition": [
      "error",
      {
        "namedComponents": [
          "function-declaration",
          "arrow-function"
        ]
      }
    ],
    "react/jsx-filename-extension": [
      1,
      {
        "extensions": [
          ".js",
          ".jsx"
        ]
      }
    ]
  }
}

Create .prettierrc.json

{
  "arrowParens": "always",
  "trailingComma": "es5",
  "singleQuote": false,
  "tabWidth": 2,
  "printWidth": 100,
  "semi": true,
  "endOfLine": "auto"
}

.prettierignore to let Prettier know what files/folders not to format

build

3. In the settings.json file

{
  // config related to code formatting
  "editor.defaultFormatter": "esbenp.prettier-vscode",
  "editor.formatOnSave": true,
  "[javascript]": {
    "editor.formatOnSave": false,
    "editor.defaultFormatter": null
  },
  "[javascriptreact]": {
    "editor.formatOnSave": false,
    "editor.defaultFormatter": null
  },
  "javascript.validate.enable": false, //disable all built-in syntax checking
  "editor.codeActionsOnSave": {
    "source.fixAll.eslint": true,
    "source.fixAll.tslint": true,
    "source.organizeImports": true
  },
  "eslint.alwaysShowStatus": true,
  // emmet
  "emmet.triggerExpansionOnTab": true,
  "emmet.includeLanguages": {
    "javascript": "javascriptreact"
  }
}

4. Finally, we have to add the scripts in the package.json

  "scripts": {
    "lint": "eslint src/**/*.{js,jsx,ts,tsx}",
    "lint:fix": "eslint --fix src/**/*.{js,jsx,ts,tsx}",
    "format": "prettier --check **/*.{js,jsx,ts,tsx}",
    "format:fix": "prettier --write src/**/*.{js,jsx,ts,tsx,css}"
  },

Polymorphism in Javascript

Polymorphism is a concept of object-oriented programming. If the child class overrides/modifies the parent class method that is called polymorphism.

// Parent Class
class Person {
    constructor () {
        this.name = "Sakib";
        this.age = 35;
    }
    play () {
        console.log(`${this.name} is playing`);
    }
}

// Child Class
class Cricketer extends Person {
    constructor () {
        super();
        this.type = "All rounder";
        this.country = "Bangladesh";
    }

    // Modified the play method
    play () {
        console.log(`${this.name} is playing cricket`);
    }
}

const sakib = new Cricketer();
sakib.play();

Static method in Javascript

class Player {
    constructor(name) {
        this.name = name;
    }

    // Normal method
    eat() {
        console.log(`${this.name} is eating`);
    }

    // Static method
    static play() {
        console.log(`I am static method`);
    }
}

let sakib = new Player('Sakib');
sakib.eat();

// Direct access to the function
Player.play();