diff --git a/docs/tekdi-style-guides/react-style-guide.md b/docs/tekdi-style-guides/react-style-guide.md index 38ff2a0..175009a 100644 --- a/docs/tekdi-style-guides/react-style-guide.md +++ b/docs/tekdi-style-guides/react-style-guide.md @@ -1,7 +1,524 @@ --- -sidebar_position: 4 +sidebar_position: 2 +tags: [react] --- # React Style Guide +## Style Guide @TODO + +## Linting, Formatting Tools +To help you assist in following style guide, we recommend **using tools suggested below, along with sample configs files suggested** to make most of these tools. + +### ESLint +Learn more about [ESLint tool](../tools/javascript/ESLint) + +#### Link to React specific docs for ESLint +- [ESLint, ESLint Plugins Installation](../tools/javascript/eslint#installation-for-react-projects-using-typescript/tools/javascript/eslint#recommended-eslint-configuration-for-react-projects-using-typescript) +- [ESLint Configuration](../tools/javascript/eslint#recommended-eslint-configuration-for-react-projects-using-typescript) + +### Prettier +Learn more about [Prettier tool](../tools/common/prettier) + +### Stylelint +Learn more about [Stylelint tool](../tools/css/stylelint) + + +<!-- Welcome to the React.js Style Guide documentation. This guide covers best practices for writing React code, setting up linters, formatters, and example configurations. + +## Example Configurations + +### ESLint Configuration + +Create a `.ESLintrc.json` file in the root of your project with the following content: + +```json +{ + "env": { + "browser": true, + "es2021": true + }, + "extends": [ + "ESLint:recommended", + "plugin:react/recommended", + "plugin:jsx-a11y/recommended", + "plugin:react-hooks/recommended", + "plugin:prettier/recommended" + ], + "parserOptions": { + "ecmaFeatures": { + "jsx": true + }, + "ecmaVersion": 12, + "sourceType": "module" + }, + "plugins": ["react", "jsx-a11y", "react-hooks", "prettier"], + "rules": { + "prettier/prettier": ["error"], + "react/react-in-jsx-scope": "off", + "react/prop-types": "off", + "no-console": "warn", + "no-unused-vars": [ + "warn", + { + "vars": "all", + "args": "after-used", + "ignoreRestSiblings": false + } + ], + "react/jsx-uses-react": "off", + "react/jsx-uses-vars": "error", + "react/jsx-filename-extension": [ + "warn", + { + "extensions": [".jsx", ".js"] + } + ], + "jsx-a11y/anchor-is-valid": [ + "warn", + { + "aspects": ["invalidHref", "preferButton"] + } + ], + "jsx-a11y/click-events-have-key-events": "warn", + "jsx-a11y/no-static-element-interactions": "warn" + }, + "settings": { + "react": { + "version": "detect" + } + } +} +``` + +### Prettier Configuration + +Create a `.prettierrc` file in the root of your project with the following content: + +```json +{ + "singleQuote": true, + "trailingComma": "es5", + "arrowParens": "avoid", + "endOfLine": "lf" +} +``` + +### Lint and Format Scripts in `package.json` + +```json +{ + "scripts": { + "lint": "ESLint 'src/**/*.{js,jsx}'", + "lint:fix": "ESLint 'src/**/*.{js,jsx}' --fix", + "format": "prettier --write 'src/**/*.{js,jsx,json,css,md}'" + } +} +``` + +## React Style Guide + +This style guide outlines the coding conventions and best practices for writing React code. Following these guidelines will help maintain consistency and readability across your React projects. + +### General Guidelines + +1. **Use Function Components** + - Prefer functional components over class components. + ```jsx + // Avoid + class MyComponent extends React.Component { + render() { + return <div>Hello, World!</div>; + } + } + + // Prefer + function MyComponent() { + return <div>Hello, World!</div>; + } + ``` + +2. **Use Hooks for State and Side Effects** + - Utilize React hooks for managing state and side effects. + ```jsx + import { useState, useEffect } from 'react'; + + function MyComponent() { + const [count, setCount] = useState(0); + + useEffect(() => { + document.title = `Count: ${count}`; + }, [count]); + + return ( + <div> + <p>{count}</p> + <button onClick={() => setCount(count + 1)}>Increment</button> + </div> + ); + } + ``` + +3. **Component Naming** + - Use PascalCase for React component names. + ```jsx + // Avoid + function mycomponent() { + return <div />; + } + + // Prefer + function MyComponent() { + return <div />; + } + ``` + +### JSX Style + +1. **Self-Closing Tags** + - Use self-closing tags for elements without children. + ```jsx + // Avoid + <img src="image.png"></img> + + // Prefer + <img src="image.png" /> + ``` + +2. **Quotes in JSX Attributes** + - Use double quotes for JSX attributes. + ```jsx + // Avoid + <div className='container'></div> + + // Prefer + <div className="container"></div> + ``` + +3. **JSX Bracket Alignment** + - Align the closing tag of a multi-line JSX element with the opening tag. + ```jsx + // Avoid + <Button + onClick={handleClick} + color="blue" + size="large" + > + Click Me + </Button> + + // Prefer + <Button + onClick={handleClick} + color="blue" + size="large" + > + Click Me + </Button> + ``` + +### Styling and CSS + +1. **CSS-in-JS** + - Use CSS-in-JS libraries like styled-components or emotion for styling. + ```jsx + import styled from 'styled-components'; + + const Button = styled.button` + background: blue; + color: white; + padding: 10px; + `; + + function App() { + return <Button>Click Me</Button>; + } + ``` + +2. **Class Names** + - Use `camelCase` for CSS class names. + ```jsx + // Avoid + <div className="container-item"></div> + + // Prefer + <div className="containerItem"></div> + ``` + +### State Management + +1. **useState for Local State** + - Use `useState` for managing local component state. + ```jsx + const [count, setCount] = useState(0); + ``` + +2. **useReducer for Complex State** + - Use `useReducer` for more complex state logic. + ```jsx + const initialState = { count: 0 }; + + function reducer(state, action) { + switch (action.type) { + case 'increment': + return { count: state.count + 1 }; + case 'decrement': + return { count: state.count - 1 }; + default: + throw new Error(); + } + } + + function Counter() { + const [state, dispatch] = useReducer(reducer, initialState); + return ( + <div> + <p>{state.count}</p> + <button onClick={() => dispatch({ type: 'increment' })}>Increment</button> + <button onClick={() => dispatch({ type: 'decrement' })}>Decrement</button> + </div> + ); + } + ``` +``` + +## ESLint Configuration + +### Installation + +To install ESLint and the necessary plugins, run: + +```bash +npm install ESLint ESLint-plugin-react ESLint-plugin-jsx-a11y ESLint-plugin-react-hooks --save-dev +``` + +### Example Configuration + +Create a `.ESLintrc.json` file in the root of your project with the following content: + +```json +{ + "env": { + "browser": true, + "es2021": true + }, + "extends": [ + "ESLint:recommended", + "plugin:react/recommended", + "plugin:jsx-a11y/recommended", + "plugin:react-hooks/recommended", + "plugin:prettier/recommended" + ], + "parserOptions": { + "ecmaFeatures": { + "jsx": true + }, + "ecmaVersion": 12, + "sourceType": "module" + }, + "plugins": ["react", "jsx-a11y", "react-hooks", "prettier"], + "rules": { + "prettier/prettier": ["error"], + "react/react-in-jsx-scope": "off", + "react/prop-types": "off", + "no-console": "warn", + "no-unused-vars": [ + "warn", + { + "vars": "all", + "args": "after-used", + "ignoreRestSiblings": false + } + ], + "react/jsx-uses-react": "off", + "react/jsx-uses-vars": "error", + "react/jsx-filename-extension": [ + "warn", + { + "extensions": [".jsx", ".js"] + } + ], + "jsx-a11y/anchor-is-valid": [ + "warn", + { + "aspects": ["invalidHref", "preferButton"] + } + ], + "jsx-a11y/click-events-have-key-events": "warn", + "jsx-a11y/no-static-element-interactions": "warn" + }, + "settings": { + "react": { + "version": "detect" + } + } +} +``` + +### Linting Scripts + +Add the following scripts to your `package.json`: + +```json +{ + "scripts": { + "lint": "ESLint 'src/**/*.{js,jsx}'", + "lint:fix": "ESLint 'src/**/*.{js,jsx}' --fix" + } +} +``` + +### Run ESLint + +The `lint` script runs ESLint on all JavaScript (.js) and JSX (.jsx) files within the src directory of your project. + +Now you can lint your project by running: + +```bash +npm run lint +``` + +or + +```bash +yarn lint +``` + +### Run ESLint Fix + +The `lint:fix` script not only runs ESLint on all JavaScript and JSX files within the src directory but also attempts to automatically fix any fixable linting errors. + +Now you can lint:fix your project by running: + +```bash +npm run lint:fix +``` + +or + +```bash +yarn lint:fix +``` + + +## Prettier Configuration + +### Introduction + +Prettier is an opinionated code formatter that supports many languages and integrates with most editors. It removes all original styling and ensures that all outputted code conforms to a consistent style. + +### Installation + +To install Prettier and the necessary plugins, run: + +```bash +npm install prettier ESLint-config-prettier ESLint-plugin-prettier --save-dev +``` + +### Example Configuration + +Create a `.prettierrc` file in the root of your project with the following content: + +```json +{ + "singleQuote": true, + "trailingComma": "es5", + "arrowParens": "avoid", + "endOfLine": "lf" +} +``` + +### Formatting Scripts + +Add the following scripts to your `package.json`: + +```json +{ + "scripts": { + "format": "prettier --write 'src/**/*.{js,jsx,json,css,md}'" + } +} +``` + +### Running Prettier + +To format your code using Prettier, run the following command: + +```bash +npm run format +``` + +or + +```bash +yarn format +``` + +This will format all JavaScript, JSX, JSON, CSS, and Markdown files in the src directory and its subdirectories. + +### Prettier Configuration File Examples + +Here are some additional examples of Prettier configuration files. + +`.prettierrc.json` + +```json +{ + "printWidth": 80, + "tabWidth": 2, + "useTabs": false, + "semi": true, + "singleQuote": true, + "quoteProps": "as-needed", + "jsxSingleQuote": false, + "trailingComma": "es5", + "bracketSpacing": true, + "jsxBracketSameLine": false, + "arrowParens": "avoid", + "proseWrap": "preserve", + "htmlWhitespaceSensitivity": "css", + "endOfLine": "lf" +} +``` + +`.prettierrc.yaml` + +```yaml +printWidth: 80 +tabWidth: 2 +useTabs: false +semi: true +singleQuote: true +quoteProps: "as-needed" +jsxSingleQuote: false +trailingComma: "es5" +bracketSpacing: true +jsxBracketSameLine: false +arrowParens: "avoid" +proseWrap: "preserve" +htmlWhitespaceSensitivity: "css" +endOfLine: "lf" +``` + +`.prettierrc.js` + +```js +module.exports = { + printWidth: 80, + tabWidth: 2, + useTabs: false, + semi: true, + singleQuote: true, + quoteProps: 'as-needed', + jsxSingleQuote: false, + trailingComma: 'es5', + bracketSpacing: true, + jsxBracketSameLine: false, + arrowParens: 'avoid', + proseWrap: 'preserve', + htmlWhitespaceSensitivity: 'css', + endOfLine: 'lf', +}; +``` + --> diff --git a/docs/tools/common/_category_.json b/docs/tools/common/_category_.json new file mode 100644 index 0000000..20c815c --- /dev/null +++ b/docs/tools/common/_category_.json @@ -0,0 +1,8 @@ +{ + "label": "Common Tools", + "position": 99, + "link": { + "type": "generated-index", + "description": "Know more about recommended Common tools" + } +} diff --git a/docs/tools/common/prettier.md b/docs/tools/common/prettier.md new file mode 100644 index 0000000..973532f --- /dev/null +++ b/docs/tools/common/prettier.md @@ -0,0 +1,108 @@ +--- +sidebar_position: 2 +tags: [css, styleguide] +--- + +# Prettier + +@TODO + +<!-- ## About +- Stylelint is a powerful tool for linting CSS and other stylesheet languages. It helps maintain consistent styles and catch potential errors in your CSS code. +- Stylelint analyzes your CSS code without actually running it. It checks for errors, enforces a coding standard, looks for code smells. + +### Links +- [Stylelint Homepage](https://stylelint.io/) + +### Stylelint Plugins +Along with stylelint, we recommend to use following plugins: +- [stylelint-config-standard](https://www.npmjs.com/package/stylelint-config-standard): is a widely-used configuration for Stylelint, providing a set of standard rules and best practices for CSS and SCSS code quality, ensuring consistency and reducing potential errors +- [stylelint-config-rational-order](https://www.npmjs.com/package/stylelint-config-rational-order): plugin organizes CSS properties in a specific, rational order, improving readability and maintainability by enforcing a logical sequence for property declarations. + +:::info +The stylelint-config-rational-order plugin's rational order is based on grouping CSS properties by their functions and logical significance. This typically involves organizing properties into categories like: +- Positioning (e.g., position, top, right, bottom, left, z-index) +- Box Model (e.g., display, width, height, margin, padding, border) +- Typography (e.g., font-family, font-size, font-weight, line-height, color) +- Visual (e.g., background, box-shadow, opacity) +- Miscellaneous (e.g., transition, transform, animation) +::: + +This structured approach improves the readability and maintainability of CSS code by grouping related properties together. + +## Installation +- First, navigate to your project directory and install Stylelint along with some essential plugins and configurations. +- If using npm +``` +npm install stylelint stylelint-config-standard stylelint-config-rational-order --save-dev +``` +- Or if using yarn +``` +yarn add stylelint stylelint-config-standard stylelint-config-rational-order --dev +``` + +:::warning +Remember to save these as `devDependencies` in your project. +::: + +## Config file for .stylelintrc +- Create and use a file named `.stylelintrc.json` in your python project root folder +- You can use the `.stylelintrc.json` file contents given below + +```JSON +{ + "extends": [ + "stylelint-config-standard", + "stylelint-config-rational-order", + ], + "ignoreFiles": [ + "**/*.min.css", + "**/*.min.js" + ] +} +``` + +### package.json commands for Stylelint +To easily run Stylelint, add the following scripts to your package.json file: + +```JSON +"scripts": { + "lint:css": "stylelint '**/*.{css,scss}'", + "lint:css:fix": "stylelint '**/*.{css,scss}' --fix" +} +``` + +## How to use Stylelint? +### A) Using stylelint outside the editor, via terminal +- Goto your project repo `cd my-web-project` +- Run stylelint as +``` +npm run lint:css +or +yarn lint:css +``` +- To automatically fix linting errors, run: +``` +npm run lint:css:fix +OR +yarn lint:css:fix +``` + +### B) Using stylelint inside VSCode editor +#### 1) Install this VSCode extension for Stylelint +- [Stylelint VSCode Extension](https://marketplace.visualstudio.com/items?itemName=stylelint.vscode-stylelint) + +#### 2) VSCode Settings for stylelint +You can edit `settings.json` of VSCode as below +- To disable the built-in CSS, Less, and SCSS linters: + +```json +{ + "css.validate": false, + "less.validate": false, + "scss.validate": false +} +``` + +#### 3) Open any python file in editor +- Open `Problems` tab in console, to see linting errors if any --> \ No newline at end of file diff --git a/docs/tools/javascript/_category_.json b/docs/tools/javascript/_category_.json new file mode 100644 index 0000000..907562f --- /dev/null +++ b/docs/tools/javascript/_category_.json @@ -0,0 +1,8 @@ +{ + "label": "Javascript Tools", + "position": 2, + "link": { + "type": "generated-index", + "description": "Know more about recommended Javascript tools" + } +} diff --git a/docs/tools/javascript/eslint.md b/docs/tools/javascript/eslint.md new file mode 100644 index 0000000..9de7ffe --- /dev/null +++ b/docs/tools/javascript/eslint.md @@ -0,0 +1,220 @@ +--- +sidebar_position: 2 +tags: [javascript, linter, formatter, fixer, ESLint, styleguide] +--- + +# ESLint + +## About +- ESLint is a static code analyser for Javasvcript code. It lets you find and fix problems in your JavaScript code +- ESLint statically analyzes your code to quickly find problems. It is built into most text editors and you can run ESLint as part of your continuous integration pipeline. + +### Links +- [ESLint Homepage](https://ESLint.org/) +- [ESLint Playground](https://ESLint.org/play/) + +### ESLint Plugins +Depending upon the project need or whether you are using React or Angular or Node, you may use different ESLint plugins: + +#### For TypeScript based projects: +- [typescript-eslint](https://www.npmjs.com/package/typescript-eslint): Tooling which enables you to use TypeScript with ESLint + +#### For React based projects: +- [eslint-plugin-react](https://www.npmjs.com/package/eslint-plugin-react): Provides React specific linting rules for eslint +- [eslint-plugin-react-hooks](https://www.npmjs.com/package/eslint-plugin-react-hooks): This ESLint plugin enforces the Rules of Hooks. +- [eslint-plugin-react-refresh](https://www.npmjs.com/package/eslint-plugin-react-refresh): This ESLint plugin validate that your components can safely be updated with Fast Refresh. +- [eslint-plugin-jsx-a11y](https://www.npmjs.com/package/eslint-plugin-jsx-a11y): This plugin runs Static AST checker for accessibility rules on JSX elements. + +#### For projects using prettier as formatting tool: +##### Prettier +- [prettier](https://www.npmjs.com/package/prettier): Prettier is an opinionated code formatter. It enforces a consistent style by parsing your code and re-printing it with its own rules that take the maximum line length into account, wrapping code when necessary. + +##### ESLint plugins for Prettier +- [eslint-config-prettier](https://www.npmjs.com/package/eslint-config-prettier): Turns off all rules that are unnecessary or might conflict with Prettier. +- [eslint-plugin-prettier](https://www.npmjs.com/package/eslint-plugin-prettier): Runs Prettier as an ESLint rule and reports differences as individual ESLint issues. + +## Prerequisites +- Node.js (^18.18.0, ^20.9.0, or >=21.1.0) built with SSL support. (If you are using an official Node.js distribution, SSL is always built in.) + +## Installation +### Installation for Angular projects +```js +@TODO +``` + +### Installation for Nodejs - Expressjs projects +```js +@TODO +``` + +### Installation for Nodejs - Nestjs projects +```js +@TODO +``` + +### Installation for React projects using TypeScript +Navigate to your project directory and install npm packages required for ESLint, ESLint plugins and configurations. + +- If using npm +```sh +npm install globals \ +eslint @eslint/js typescript-eslint \ +eslint-plugin-react \ +eslint-plugin-react-hooks \ +eslint-plugin-react-refresh \ +eslint-plugin-jsx-a11y +prettier eslint-config-prettier eslint-plugin-prettier \ +--save-dev +``` + +- Or if using yarn + +```sh +yarn add globals \ +eslint @eslint/js typescript-eslint \ +eslint-plugin-react \ +eslint-plugin-react-hooks \ +eslint-plugin-react-refresh \ +eslint-plugin-jsx-a11y +prettier eslint-config-prettier eslint-plugin-prettier \ +--dev +``` + +:::warning +Remember to save these as `devDependencies` in your project. +::: + +## Config file for eslint.config.js +- From v8.21.0, eslint announced a new config system. In the new system, .eslintrc* is no longer used. eslint.config.js would be the default config file name. In eslint v8, the legacy system (.eslintrc*) would still be supported, while in eslint v9, only the new system would be supported. +- And from v8.23.0, eslint CLI starts to look up eslint.config.js. So, if your eslint is >=8.23.0, you're 100% ready to use the new config system. +- You might want to check out the official blog posts, + - https://eslint.org/blog/2022/08/new-config-system-part-1/ + - https://eslint.org/blog/2022/08/new-config-system-part-2/ + - https://eslint.org/blog/2022/08/new-config-system-part-3/ +- Create and use a file named `eslint.config.js` in your python project root folder + +### Recommended ESLint configuration for Angular projects +```js +@TODO +``` + +### Recommended ESLint configuration for Nodejs - Expressjs projects +```js +@TODO +``` + +### Recommended ESLint configuration for Nodejs - Nestjs projects +```js +@TODO +``` + +### Recommended ESLint configuration for React projects using TypeScript + +```js +import globals from 'globals'; +import pluginJs from '@eslint/js'; +import tseslint from 'typescript-eslint'; +import pluginReact from 'eslint-plugin-react'; +import pluginReactHooks from 'eslint-plugin-react-hooks'; +import pluginReactRefresh from 'eslint-plugin-react-refresh'; +import pluginJsxA11y from 'eslint-plugin-jsx-a11y'; +import pluginEslintPrettieRecommendedConfig from 'eslint-plugin-prettier/recommended'; + +/** @type {import('eslint').Linter.Config[]} */ +export default [ + { + files: ['**/*.{js,mjs,cjs,ts,jsx,tsx}'], + }, + { + languageOptions: { + globals: { + ...globals.browser, + }, + }, + }, + pluginJs.configs.recommended, + ...tseslint.configs.recommended, + pluginReact.configs.flat.recommended, + pluginJsxA11y.flatConfigs.recommended, + pluginEslintPrettieRecommendedConfig, + { + plugins: { + 'react-hooks': pluginReactHooks, + 'react-refresh': pluginReactRefresh, + }, + settings: { + react: { + version: 'detect', + }, + }, + rules: { + 'react-hooks/rules-of-hooks': 'error', + 'react-hooks/exhaustive-deps': 'warn', + 'react-refresh/only-export-components': 'warn', + // Prettier and Indentation Rules + 'prettier/prettier': [ + 'error', + { + arrowParens: 'always', + endOfLine: 'lf', + semi: true, + singleQuote: true, + tabWidth: 4, + trailingComma: 'es5', + useTabs: true, + }, + ], + indent: ['error', 'tab'], + }, + }, + { + // Optional: ignore specific files or patterns + ignores: ['**/node_modules/**', 'dist/**', 'build/**'], + }, +]; +``` + + +### Recommended ESLint configuration for React Native projects +```js +@TODO +``` + +<!-- ## How to use ESLint? +### A) Using ESLint outside the editor, via terminal +- Goto your project repo `cd my-python-project` +- Activate your project's venv `source /path-to-your-projects-env/bin/activate` +- Run ESLint as + +Example of scanning all .py files from current directory +``` +ESLint *.py +``` + +Example of scanning all files from current directory (.) recursively, ignoring .venv folder +``` +ESLint --recursive=y --ignore=.venv . +``` + +### B) Using ESLint inside VSCode editor +#### 1) Install this VSCode extension for ESLint +- [ESLint VSCode Extension](https://marketplace.visualstudio.com/items?itemName=ms-python.ESLint) + +#### 2) VSCode Settings for ESLint +You can edit `settings.json` of VSCode as below +- To run ESLint on code change +- To always show notifications + +```json +{ + "ESLint.lintOnChange": true, + "ESLint.showNotifications": "always", +} +``` + +#### 3) Open any python file in editor +- Open `Problems` tab in console, to see linting errors if any + +#### 4) References +- Read more here [Linting Python in Visual Studio Code +](https://code.visualstudio.com/docs/python/linting) --> \ No newline at end of file diff --git a/docs/tools/python/_category_.json b/docs/tools/python/_category_.json index 20dd9e0..1fe8ff4 100644 --- a/docs/tools/python/_category_.json +++ b/docs/tools/python/_category_.json @@ -1,6 +1,6 @@ { "label": "Python Tools", - "position": 2, + "position": 3, "link": { "type": "generated-index", "description": "Know more about recommended Python tools" diff --git a/docusaurus.config.ts b/docusaurus.config.ts index e822cc2..73af812 100644 --- a/docusaurus.config.ts +++ b/docusaurus.config.ts @@ -28,8 +28,8 @@ const config: Config = { // useful metadata like html lang. For example, if your site is Chinese, you // may want to replace "en" with "zh-Hans". i18n: { - defaultLocale: "en", - locales: ["en"], + defaultLocale: "en-GB", + locales: ["en-GB"], }, presets: [ @@ -43,6 +43,9 @@ const config: Config = { // Please change this to your repo. // Remove this to remove the "edit this page" links. // editUrl: 'https://github.com/facebook/docusaurus/tree/main/packages/create-docusaurus/templates/shared/', + + showLastUpdateTime: true, // ++ Tekdi + showLastUpdateAuthor: true, // ++ Tekdi }, /*blog: { showReadingTime: true,