├── .gitignore ├── logo ├── hero-dark.jpg ├── light.svg └── dark.svg ├── images ├── checks-passed.png ├── hero-light.svg └── hero-dark.svg ├── .all-contributorsrc ├── package.json ├── .todo ├── LICENSE ├── mint.json ├── development.mdx ├── resources ├── essential-resources.mdx └── must-have-tools.mdx ├── README.md ├── introduction.mdx ├── docs ├── typeScript-essentials.mdx ├── colors.mdx ├── code-documentation.mdx ├── code-optimization.mdx ├── react-code-structure.mdx ├── organizing-imports.mdx ├── secure-coding.mdx ├── programming-case-types.mdx ├── typography.mdx └── code-splitting.mdx └── favicon.svg /.gitignore: -------------------------------------------------------------------------------- 1 | node_modules -------------------------------------------------------------------------------- /logo/hero-dark.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/jacksonkasi1/docs/HEAD/logo/hero-dark.jpg -------------------------------------------------------------------------------- /images/checks-passed.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/jacksonkasi1/docs/HEAD/images/checks-passed.png -------------------------------------------------------------------------------- /.all-contributorsrc: -------------------------------------------------------------------------------- 1 | { 2 | "projectName": "docs", 3 | "projectOwner": "jacksonkasi1", 4 | "repoType": "github", 5 | "repoHost": "https://github.com", 6 | "files": [ 7 | "README.md" 8 | ], 9 | "imageSize": 100, 10 | "commit": true, 11 | "commitConvention": "gitmoji", 12 | "contributors": [], 13 | "contributorsPerLine": 7, 14 | "linkToUsage": true 15 | } 16 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "docs", 3 | "version": "1.0.0", 4 | "description": "", 5 | "main": "index.js", 6 | "scripts": { 7 | "test": "echo \"Error: no test specified\" && exit 1", 8 | "dev": "mintlify dev" 9 | }, 10 | "devDependencies": { 11 | "all-contributors-cli": "^6.26.1", 12 | "mintlify": "^4.0.114" 13 | }, 14 | "keywords": [], 15 | "author": "jacksonkasi1", 16 | "license": "MIT" 17 | } 18 | -------------------------------------------------------------------------------- /.todo: -------------------------------------------------------------------------------- 1 | # this not related to document. it's just image source to add in upcomming document img frame. 2 | 3 | good images: 4 | - https://unsplash.com/photos/train-rail-between-wall-M-obGtfDlUU 5 | - https://unsplash.com/photos/brown-and-green-rock-formation-on-body-of-water-during-daytime-hnnEiSTpgUs 6 | - https://unsplash.com/photos/photography-of-house-near-body-of-water-YwFHhIgG77M 7 | - https://unsplash.com/photos/landscape-photography-of-mountain-ranges-under-purple-and-pink-skies--g7axSVst6Y 8 | - https://unsplash.com/photos/low-angle-photography-of-fog-covered-mountain-fkqBXZbevXg 9 | - https://unsplash.com/photos/brown-wooden-boat-moving-towards-the-mountain-O453M2Liufs 10 | - https://unsplash.com/photos/black-building-on-gray-rock-hill-eE2trMn-6a0 11 | - https://unsplash.com/photos/person-in-yellow-coat-standing-on-top-of-hill-BkkVcWUgwEk 12 | - https://unsplash.com/photos/concrete-road-between-mountains-Kt5hRENuotI 13 | - https://unsplash.com/photos/brown-wooden-cabin-on-body-of-water-jb1Mc1lv8X0 14 | - https://unsplash.com/photos/lava-dripping-to-ocean-E4944K_4SvI -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2024 Jackson Kasi 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /mint.json: -------------------------------------------------------------------------------- 1 | { 2 | "$schema": "https://mintlify.com/schema.json", 3 | "name": "Developer Best Practices", 4 | "logo": { 5 | "dark": "/logo/dark.svg", 6 | "light": "/logo/light.svg" 7 | }, 8 | "favicon": "/favicon.svg", 9 | "colors": { 10 | "primary": "#0D9373", 11 | "light": "#07C983", 12 | "dark": "#0D9373", 13 | "anchors": { 14 | "from": "#0D9373", 15 | "to": "#07C983" 16 | } 17 | }, 18 | "feedback": { 19 | "suggestEdit": true, 20 | "raiseIssue": true, 21 | "thumbsRating": true 22 | }, 23 | "topbarCtaButton": { 24 | "type": "github", 25 | "url": "https://github.com/jacksonkasi1/docs" 26 | }, 27 | "topbarLinks": [ 28 | { 29 | "name": "Support", 30 | "url": "mailto:jacksonkasipeacock@gmail.com" 31 | } 32 | ], 33 | "tabs": [], 34 | "anchors": [ 35 | { 36 | "name": "Documentation", 37 | "icon": "book-open-cover", 38 | "url": "https://peacockindia.mintlify.app" 39 | }, 40 | { 41 | "name": "Github", 42 | "icon": "github", 43 | "url": "https://github.com/jacksonkasi1/docs" 44 | } 45 | ], 46 | "navigation": [ 47 | { 48 | "group": "Get Started", 49 | "pages": ["introduction", "development"] 50 | }, 51 | { 52 | "group": "Developer Best Practices ⚒️", 53 | "pages": [ 54 | "docs/organizing-imports", 55 | "docs/colors", 56 | "docs/typography", 57 | "docs/programming-case-types", 58 | "docs/react-code-structure", 59 | "docs/code-documentation", 60 | "docs/code-splitting", 61 | "docs/typeScript-essentials", 62 | "docs/code-optimization", 63 | "docs/secure-coding" 64 | ] 65 | }, 66 | { 67 | "group": "Essential Resources 📖", 68 | "pages": ["resources/essential-resources", "resources/must-have-tools"] 69 | } 70 | ], 71 | "footerSocials": { 72 | "twitter": "https://twitter.com/jacksonkasi11", 73 | "github": "https://github.com/jacksonkasi1", 74 | "linkedin": "https://www.linkedin.com/in/jacksonkasi" 75 | }, 76 | "analytics": { 77 | "clearbit": { 78 | "publicApiKey": "pk_67d3962d6ff22e060f66565c16985ee4" 79 | } 80 | } 81 | } 82 | -------------------------------------------------------------------------------- /development.mdx: -------------------------------------------------------------------------------- 1 | --- 2 | title: "Development Documentation Progress Tracker 📋" 3 | sidebarTitle: "Documentation Tracker" 4 | description: "A tracker for monitoring the progress of various development documentation pages." 5 | icon: "clipboard-list" 6 | --- 7 | 8 | Keep track of completed and pending documentation pages for software development best practices with this handy tracker. 9 | 10 | ## Completed Documentation Pages ✅ 11 | 12 | - [x] **Organizing Imports** 13 | - Guidelines on how to structure and order import statements. 14 | 15 | - [x] **Centralized Typography** 16 | - Discusses the implementation of a consistent typographic system. 17 | 18 | - [x] **Managing Colors** 19 | - Covers best practices for color management using various methods. 20 | 21 | - [x] **Code Splitting** 22 | - Provides insights into efficient code organization and separation. 23 | 24 | - [x] **Naming Conventions** 25 | - Details on naming files, functions, variables, and more. 26 | 27 | - [x] **Code Documentation** 28 | - Discusses the importance and methods of proper code documentation. 29 | 30 | - [x] **TypeScript Essentials** 31 | - Outlines key concepts and practices in TypeScript development. 32 | 33 | - [x] **React Code Structure** 34 | - Focuses on best practices for structuring React applications. 35 | 36 | - [x] **Code Optimization** 37 | - Covers strategies for improving code efficiency and performance. 38 | 39 | - [x] **Secure Coding** 40 | - Addresses security concerns and practices in web development. 41 | 42 | ## Pending Documentation Pages 📝 43 | 44 | - [ ] **Responsive Design Practices** 45 | - Strategies for crafting responsive layouts and interfaces. 46 | 47 | - [ ] **Etc...** 48 | - Additional topics to be included in the future. 49 | 50 | 51 | --- 52 | 53 | ## 🌟 Your Contributions Are Valuable! 🌟 54 | 55 | This documentation thrives on community insights! Here's how you can make a difference: 56 | 57 | 1. **Spot an Error?** 🕵️‍♂️ Let us know! Help us keep the information accurate. 58 | 2. **Got a Great Idea?** 💡 Submit a pull request with your awesome additions. 59 | 3. **Suggest Topics:** 🌿 Have ideas for new content? Share them! 60 | 4. **Share Your Experience:** 📚 Your unique insights can enrich our content. 61 | 5. **Know of Resources or Articles?** 📖 Contribute to our growing list of helpful materials. 62 | 63 | Remember, every contributor will be acknowledged in our `readme.md` and on the relevant documentation pages! Your insights make a difference! 🙌 -------------------------------------------------------------------------------- /resources/essential-resources.mdx: -------------------------------------------------------------------------------- 1 | --- 2 | title: "Essential Resources for Developers and Designers" 3 | sidebarTitle: "Resource List" 4 | description: "An ever-growing compilation of invaluable guides, articles, and documentation to elevate the skills of developers and designers." 5 | icon: "bookmark" 6 | og:site_name: "Developer's and Designer's Hub" 7 | og:title: "Essential Resources for Developers and Designers" 8 | og:description: "Explore a curated list of resources including guides, articles, and documentation vital for developers and designers." 9 | og:url: "https://peacockindia.mintlify.app/resources/essential-resources" 10 | og:image: "https://images.unsplash.com/photo-1473654729523-203e25dfda10?q=80&w=3270&auto=format&fit=crop&ixlib=rb-4.0.3&ixid=M3wxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8fA%3D%3D" 11 | og:image:width: "1200" 12 | og:image:height: "630" 13 | og:locale: "en_US" 14 | article:publisher: "https://github.com/jacksonkasi1" 15 | twitter:title: "Essential Resources for Developers and Designers" 16 | twitter:description: "Curated resources to boost the skills and knowledge of developers and designers." 17 | twitter:url: "https://peacockindia.mintlify.app/resources/essential-resources" 18 | twitter:image: "https://images.unsplash.com/photo-1473654729523-203e25dfda10?q=80&w=3270&auto=format&fit=crop&ixlib=rb-4.0.3&ixid=M3wxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8fA%3D%3D" 19 | twitter:site: "@jacksonkasi11" 20 | --- 21 | 22 | 23 | Using a Centralized Typography Component in React 28 | 29 | 30 | This living document is a collection of outstanding guides, articles, and documentation aimed at enhancing the productivity and skills of programmers and designers. It will be updated periodically with new and insightful resources. 31 | 32 | ## Design Guidelines and UI/UX 33 | 34 | - [Shopify Design Guidelines](https://shopify.dev/docs/apps/design-guidelines) 35 | - Comprehensive design principles and best practices for creating apps within the Shopify ecosystem. 36 | 37 | - [Polaris - Shopify Design System](https://polaris.shopify.com/) 38 | - A detailed design system that helps create a consistent user experience for Shopify products. 39 | 40 | ## Coding Practices 41 | 42 | - [Good Coding Practices by Qulix Systems](https://www.qulix.com/about/blog/good-coding-practices/) 43 | - An article that outlines practical advice for writing clean and maintainable code. 44 | 45 | ## Additional Recommended Resources 46 | 47 | - [Google's Web Fundamentals](https://developers.google.com/web/fundamentals) 48 | - Google's best practices for building a modern, performant web experience. 49 | 50 | - [Mozilla Developer Network (MDN) Web Docs](https://developer.mozilla.org/) 51 | - A premier resource for web developers, offering comprehensive documentation and learning materials for web technologies. 52 | 53 | Remember, the journey of learning and improvement never ends. Keep this list handy as a gateway to evolving your craft. 54 | 55 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Developer Best Practices Documentation 2 | 3 | ![GitHub contributors](https://img.shields.io/github/contributors/jacksonkasi1/docs?style=for-the-badge) 4 | 5 | 6 | Welcome to the Developer Best Practices Documentation - a comprehensive guide for coding enthusiasts and professionals alike. 7 | 8 | ## Introduction 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | Developer Best Practices Documentation 19 | 20 | 21 | 22 | 23 | This documentation covers a wide range of topics from code optimization, secure coding practices, best practices in various programming languages, to the latest trends in software development. 24 | 25 | ## Documentation Pages 26 | 27 | - Organizing Imports 28 | - Managing Colors 29 | - Centralized Typography 30 | - Naming Conventions 31 | - React Code Structure 32 | - Code Documentation 33 | - TypeScript Essentials 34 | - Code Optimization 35 | - Secure Coding 36 | - [More...](https://peacockindia.mintlify.app) 37 | 38 | ## Contributing 39 | 40 | We welcome contributions from the community! Whether it's fixing a bug, improving the documentation, or sharing a new topic, your input is valuable. 41 | 42 | To contribute: 43 | 1. Fork the repository. 44 | 2. Make your changes. 45 | 3. Submit a pull request. 46 | 47 | For detailed contribution guidelines, visit [our contribution page](https://peacockindia.mintlify.app/development#your-contributions-are-valuable). 48 | 49 | 50 | ## Contributors 🌟 51 | 52 | Special thanks to everyone who has contributed to making this documentation better! Your knowledge and experiences have been invaluable. 53 | 54 | 55 | 56 | 57 | 58 | 59 | 60 | 61 | 62 | 63 | 69 | 75 | 76 |
64 | 65 | Jackson Kasi 66 | 67 |

Jackson Kasi

68 |
70 | 71 | Peeyusj 72 | 73 |

Peeyusj

74 |
77 | 78 | ## License 79 | 80 | This guide is open-source and is available under the [MIT License](LICENSE). 81 | 82 | --- 83 | 84 | Maintained with 💙 by [Jackson kasi](https://github.com/jacksonkasi1) 85 | 86 | Happy Coding! 🚀 87 | -------------------------------------------------------------------------------- /introduction.mdx: -------------------------------------------------------------------------------- 1 | --- 2 | title: "Introduction to Better Code Practices" 3 | sidebarTitle: "Introduction" 4 | description: "Kickstart your journey to more efficient and error-less coding with our developer's guide to better code practices." 5 | icon: "lightbulb" 6 | og:site_name: "Developer's Guide to Efficiency" 7 | og:title: "Introduction to Better Code Practices" 8 | og:description: "Begin your path to improved coding techniques and practices with insights from experts." 9 | og:url: "https://peacockindia.mintlify.app/introduction" 10 | og:image: "https://res.cloudinary.com/dlmbwxi0u/image/upload/c_pad,b_auto:predominant,fl_preserve_transparency/v1706589750/hero-dark_tpf2wy.jpg?_s=public-apps" 11 | og:image:width: "1200" 12 | og:image:height: "630" 13 | og:locale: "en_US" 14 | article:publisher: "https://github.com/jacksonkasi1" 15 | twitter:title: "Introduction to Better Code Practices" 16 | twitter:description: "Embark on a journey to master efficient and error-less coding practices." 17 | twitter:url: "https://res.cloudinary.com/dlmbwxi0u/image/upload/c_pad,b_auto:predominant,fl_preserve_transparency/v1706589750/hero-dark_tpf2wy.jpg?_s=public-apps" 18 | twitter:image: "/images/hero-dark.jpg" 19 | twitter:site: "@jacksonkasi11" 20 | --- 21 | 22 | Hero Light 27 | Hero Dark 32 | 33 | # 🚀 Enhancing Code Quality and Maintainability 🛠️ 34 | 35 | Hello there! I'm [**Jackson Kasi**](https://github.com/jacksonkasi1), and I've put together this document to share some essential insights and best practices in web development. My journey in coding has been filled with various challenges, and I've learned a lot along the way. Now, I want to pass on these learnings to help you avoid common pitfalls and improve your coding practices. 🌟 36 | 37 | ## Why This Document? 🤔 38 | 39 | The world of coding is vast and often challenging, filled with opportunities for both learning and improvement: 40 | 41 | - **Addressing Common Challenges**: Throughout my coding journey, I've encountered a myriad of challenges. This guide is an effort to help you tackle similar hurdles, ensuring a smoother coding experience. 🛑 42 | 43 | - **Simplifying Best Practices**: My goal is to break down sophisticated coding practices into digestible, actionable steps. This guide covers a range of topics, from effective code structuring to advanced development techniques, catering to developers at all levels. ✅ 44 | 45 | - **From One Developer to Another**: Having been in the trenches myself, I understand the intricacies and nuances of coding. This guide is crafted to be practical, relatable, and easy to follow, aiming to resonate with your development journey. 🚶‍♂️🚶‍♀️ 46 | 47 | ## Benefits for Developers 🌈 48 | 49 | - **Readability and Maintenance**: Learn to structure your code for easy reading and maintenance, saving you and your team countless hours of head-scratching. 🧐 50 | 51 | - **Scalable Code Architecture**: Discover how to build a codebase that's not only robust but also scalable, making it easier to handle as your project grows. 🌱 52 | 53 | - **Enhanced Collaboration**: With clear and organized code, collaborating with other developers becomes a breeze, leading to more efficient teamwork. 🤝 54 | 55 | - **Quality and Efficiency**: Adopting these practices will not only improve the quality of your code but also make your development process more efficient and enjoyable. 🎯 56 | 57 | So, let's dive in and explore how we can make your coding journey smoother, more efficient, and a lot more fun! 🚀👩‍💻👨‍💻 58 | 59 | ## Explore the Topics 🌎 60 | 61 | 62 | 67 | Best Practices for Developers 68 | 69 | 70 | 75 | Resources for Developers 76 | 77 | 78 | -------------------------------------------------------------------------------- /docs/typeScript-essentials.mdx: -------------------------------------------------------------------------------- 1 | --- 2 | title: "Mastering TypeScript: Best Practices and Pitfalls" 3 | sidebarTitle: "TypeScript Essentials" 4 | description: "Explore the strengths of TypeScript in enhancing code quality, along with guidelines for best practices and pitfalls to avoid." 5 | icon: "code" 6 | og:site_name: "TypeScript Mastery" 7 | og:title: "Mastering TypeScript: Best Practices and Pitfalls" 8 | og:description: "Dive into the world of TypeScript, learning key best practices and common pitfalls to achieve cleaner, more robust code." 9 | og:url: "https://peacockindia.mintlify.app/docs/typeScript-essentials" 10 | og:image: "https://images.unsplash.com/photo-1659565763321-37c48ced160f?q=80&w=3270&auto=format&fit=crop&ixlib=rb-4.0.3&ixid=M3wxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8fA%3D%3D" 11 | og:image:width: "1200" 12 | og:image:height: "630" 13 | og:locale: "en_US" 14 | article:publisher: "https://github.com/jacksonkasi1" 15 | twitter:title: "Mastering TypeScript: Best Practices and Pitfalls" 16 | twitter:description: "Guidance on leveraging TypeScript for improved code quality and avoiding common errors." 17 | twitter:url: "https://peacockindia.mintlify.app/docs/typeScript-essentials" 18 | twitter:image: "https://images.unsplash.com/photo-1659565763321-37c48ced160f?q=80&w=3270&auto=format&fit=crop&ixlib=rb-4.0.3&ixid=M3wxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8fA%3D%3D" 19 | twitter:site: "@jacksonkasi11" 20 | --- 21 | 22 | 23 | Using a Centralized Typography Component in React 28 | 29 | 30 | TypeScript, an extension of JavaScript, provides powerful typing and object-oriented features. This guide highlights the advantages of TypeScript and offers advice on best practices, as well as pitfalls to avoid for effective TypeScript development. 31 | 32 | ## Why TypeScript? 33 | 34 | TypeScript enhances JavaScript by adding static types. Benefits include: 35 | 36 | - **Early Error Detection**: TypeScript identifies errors during compilation, reducing runtime errors. 37 | - **Code Readability**: Type annotations make the code more understandable. 38 | - **Easier Refactoring**: Safe and predictable code modifications. 39 | - **Richer IDE Support**: Better autocompletion, navigation, and hints. 40 | 41 | ## TypeScript Best Practices 42 | 43 | ### Define Clear Types 44 | 45 | **Good Practice**: Always define clear and specific types. 46 | 47 | ```typescript 48 | function greet(name: string): string { 49 | return `Hello, ${name}`; 50 | } 51 | ``` 52 | 53 | **Bad Practice**: Avoid using 'any' type unless absolutely necessary. 54 | 55 | ```typescript 56 | function greet(name: any): any { 57 | return `Hello, ${name}`; 58 | // 'any' type defeats the purpose of TypeScript 59 | } 60 | ``` 61 | 62 | ### Use Interface for Object Types 63 | 64 | **Good Practice**: Use interfaces to describe object shapes. 65 | 66 | ```typescript 67 | interface User { 68 | name: string; 69 | age: number; 70 | } 71 | 72 | const user: User = { name: "Alice", age: 30 }; 73 | ``` 74 | 75 | **Bad Practice**: Avoid inline type definitions for objects. 76 | 77 | ```typescript 78 | const user: { name: string; age: number } = { name: "Alice", age: 30 }; 79 | // Inline types are harder to maintain 80 | ``` 81 | 82 | ### Leverage Union Types for Flexibility 83 | 84 | **Good Practice**: Use union types for variables that might hold different types. 85 | 86 | ```typescript 87 | let id: string | number; 88 | id = "123"; // valid 89 | id = 123; // also valid 90 | ``` 91 | 92 | **Bad Practice**: Overusing union types can lead to unclear code. 93 | 94 | ```typescript 95 | let value: string | number | boolean | User; 96 | // Too many types can make the code less predictable 97 | ``` 98 | 99 | ## TypeScript Pitfalls to Avoid 100 | 101 | ### Overcomplicating Types 102 | 103 | Avoid creating overly complex or nested types that can make the code hard to understand and maintain. 104 | 105 | ### Ignoring Compiler Warnings 106 | 107 | TypeScript's compiler warnings are valuable for catching potential issues. Ignoring them defeats the benefits of using TypeScript. 108 | 109 | ### Inconsistent Naming Conventions 110 | 111 | Just like in JavaScript, maintain consistent naming conventions in TypeScript to ensure code clarity and consistency. 112 | 113 | --- 114 | 115 | TypeScript, when used effectively, can significantly improve the quality of your JavaScript code. Embracing its features and adhering to best practices will lead to more robust, maintainable, and scalable applications. Remember, the goal is not just to satisfy the TypeScript compiler, but to write clearer, safer, and more efficient code. 116 | -------------------------------------------------------------------------------- /favicon.svg: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /docs/colors.mdx: -------------------------------------------------------------------------------- 1 | --- 2 | title: "Effective Color Management in Web Development" 3 | sidebarTitle: "Managing Colors" 4 | description: "A comprehensive guide on managing colors using Tailwind CSS, CSS variables, and JSX, including good and bad practices." 5 | icon: "palette" 6 | og:site_name: "Web Design Insights" 7 | og:title: "Effective Color Management in Web Development" 8 | og:description: "Explore the art of color management in web projects using modern CSS techniques and tools." 9 | og:url: https://peacockindia.mintlify.app/docs/colors 10 | og:image: "https://images.unsplash.com/photo-1519681393784-d120267933ba?q=80&w=3270&auto=format&fit=crop&ixlib=rb-4.0.3" 11 | og:image:width: "1200" 12 | og:image:height: "630" 13 | og:locale: "en_US" 14 | article:publisher: "https://github.com/jacksonkasi1" 15 | twitter:title: "Effective Color Management in Web Development" 16 | twitter:description: "Master color management in your web development projects for a visually cohesive and accessible user experience." 17 | twitter:url: https://peacockindia.mintlify.app/docs/colors 18 | twitter:image: "https://images.unsplash.com/photo-1519681393784-d120267933ba?q=80&w=3270&auto=format&fit=crop&ixlib=rb-4.0.3" 19 | twitter:site: "@jacksonkasi11" 20 | --- 21 | 22 | 23 | Using a Centralized Typography Component in React 28 | 29 | 30 | Proper color management is essential in web development for maintaining a consistent and scalable design. This document outlines best practices for managing colors using Tailwind CSS, CSS variables, and JSX. It also highlights common pitfalls to avoid. 31 | 32 | ## Bad Practices to Avoid 📛 33 | 34 | Before diving into the best practices, it's important to understand what to avoid. 35 | 36 | ### Inline Color Definitions 37 | 38 | Avoid defining colors directly within your components or CSS classes. This leads to inconsistency and makes it difficult to update or maintain your color scheme. 39 | 40 | ```css 41 | /* Bad Practice in css */ 42 | .some-class { 43 | color: #333333; /* Direct color definition */ 44 | background-color: #ffffff; /* Hardcoded color */ 45 | } 46 | ``` 47 | 48 | ```js 49 | /* Bad Practice in JSX */ 50 | const MyComponent = () => ( 51 |
52 | Content 53 |
54 | ); 55 | ``` 56 | 57 | ## Using CSS Variables for Global Color Management 🎨 58 | 59 | CSS variables offer a flexible and maintainable approach to manage colors globally. 60 | 61 | ### Defining CSS Variables 62 | 63 | ```css 64 | :root { 65 | --primary-color: #5A67D8; 66 | --secondary-color: #ED64A6; 67 | --text-color: #333333; 68 | --background-color: white; 69 | --warning-color: #ffcc00; 70 | } 71 | ``` 72 | 73 | ### Using CSS Variables in Stylesheets 74 | 75 | ```css 76 | .header { 77 | background-color: var(--primary-color); 78 | color: var(--background-color); 79 | } 80 | ``` 81 | 82 | ### Dark Mode Example with CSS Variables 83 | 84 | ```css 85 | .dark { 86 | --primary-color: #9f7aea; 87 | --background-color: #2d3748; 88 | --text-color: #cbd5e0; 89 | } 90 | ``` 91 | 92 | ### Tailwind CSS for Consistent Color Usage 93 | 94 | Tailwind CSS provides a utility-first approach, allowing you to define a color palette in your configuration and use it throughout your project. 95 | 96 | ### Defining Colors in Tailwind Configuration 97 | 98 | ```js tailwind.config.js 99 | module.exports = { 100 | theme: { 101 | extend: { 102 | colors: { 103 | primary: '#5A67D8', 104 | secondary: '#ED64A6', 105 | // other colors... 106 | }, 107 | }, 108 | }, 109 | // other configurations... 110 | }; 111 | ``` 112 | 113 | ### Using Tailwind Classes in JSX 114 | 115 | ```js 116 | const MyComponent = () => ( 117 |

Welcome to My Site

118 | ); 119 | ``` 120 | 121 | ## Managing Colors in JSX with CSS Variables 122 | 123 | Incorporating CSS variables in JSX provides a seamless way to apply global color themes in React components. 124 | 125 | ### Good Practice in JSX 126 | 127 | ```js 128 | const MyComponent = () => ( 129 |
130 | Welcome 131 |
132 | ); 133 | ``` 134 | 135 | ## Useful Links and Resources 136 | 137 | - **Tailwind CSS Documentation**: [Tailwind CSS Customization](https://tailwindcss.com/docs/customizing-colors) 138 | - **CSS Variables Guide**: [MDN Web Docs on CSS Custom Properties](https://developer.mozilla.org/en-US/docs/Web/CSS/Using_CSS_custom_properties) 139 | - **Color Palette Generators**: 140 | - [Coolors.co](https://coolors.co) 141 | - [Tailwind CSS Color Generator](https://uicolors.app/create) 142 | - [Adobe Color Wheel](https://color.adobe.com/create/color-wheel) 143 | - [UI Colors](https://uicolors.app/create) 144 | - **Accessibility in Colors**: 145 | - [Contrast Checker](https://coolors.co/contrast-checker/112a46-acc8e5) 146 | - [Webaim Contrast Checker](https://webaim.org/resources/contrastchecker) 147 | - [A11y - Color Palette Accessibility Checker](https://color.a11y.com) 148 | - **Chakra UI Theming**: [Chakra UI Customization](https://chakra-ui.com/docs/styled-system/customize-theme) 149 | - **Shadcn UI Theming**: [Shadcn UI Customization](https://ui.shadcn.com/themes) 150 | 151 | 152 | ## Conclusion 153 | 154 | By following these best practices, you can ensure a cohesive, maintainable, and scalable approach to color management in your web development projects. Whether using CSS variables, Tailwind CSS, or JSX styling, centralizing and standardizing your color definitions will greatly enhance the consistency and flexibility of your design system. -------------------------------------------------------------------------------- /docs/code-documentation.mdx: -------------------------------------------------------------------------------- 1 | --- 2 | title: "Best Practices in Code Documentation and Formatting" 3 | sidebarTitle: "Code Documentation" 4 | description: "Learn the essentials of using JSDoc, and effective commenting, along with indentation and formatting best practices." 5 | icon: "book" 6 | og:site_name: "Developer's Guide" 7 | og:title: "Best Practices in Code Documentation and Formatting" 8 | og:description: "Learn the essentials of using JSDoc, and effective commenting, along with indentation and formatting best practices." 9 | og:url: "https://peacockindia.mintlify.app/docs/code-documentation" 10 | og:image: "https://images.unsplash.com/photo-1553198194-1b81858f6436?q=80&w=3270&auto=format&fit=crop&ixlib=rb-4.0.3&ixid=M3wxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8fA%3D%3D" 11 | og:image:width: "1200" 12 | og:image:height: "630" 13 | og:locale: "en_US" 14 | article:publisher: "https://github.com/jacksonkasi1" 15 | twitter:title: "Best Practices in Code Documentation and Formatting" 16 | twitter:description: "Learn the essentials of using JSDoc, and effective commenting, along with indentation and formatting best practices." 17 | twitter:url: "https://peacockindia.mintlify.app/docs/code-documentation" 18 | twitter:image: "https://images.unsplash.com/photo-1553198194-1b81858f6436?q=80&w=3270&auto=format&fit=crop&ixlib=rb-4.0.3&ixid=M3wxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8fA%3D%3D" 19 | twitter:site: "@jacksonkasi11" 20 | --- 21 | 22 | 23 | Best Practices for Import Statements in React 28 | 29 | 30 | Effective documentation and consistent formatting are key to making code readable and maintainable. This guide covers the usage of JSDoc and the dos and don'ts of commenting and formatting. 31 | 32 | ## JSDoc for JavaScript 33 | 34 | JSDoc is a popular tool for documenting JavaScript code. It helps in understanding the purpose of functions, parameters, and return types. 35 | 36 | ### Good JSDoc Example 37 | 38 | ```js 39 | /** 40 | * Adds two numbers together. 41 | * @param {number} a - The first number. 42 | * @param {number} b - The second number. 43 | * @returns {number} The sum of the two numbers. 44 | */ 45 | function sum(a, b) { 46 | return a + b; 47 | } 48 | ``` 49 | 50 | ### Bad JSDoc Example 51 | 52 | ```js 53 | // Adds a and b 54 | function sum(a, b) { 55 | return a + b; 56 | } 57 | // Missing detailed JSDoc comment 58 | ``` 59 | 60 | ## Proper Use of Multi-Line Comments 61 | 62 | Multi-line comments are useful for providing detailed explanations or summarizing blocks of code. 63 | 64 | ### Good Multi-Line Commenting Practice 65 | 66 | ```js 67 | /** 68 | * This function calculates the total price of an order 69 | * including tax and discount. It applies a tax rate of 8%, 70 | * and a discount rate is applied if applicable. 71 | * 72 | * @param {number} basePrice - The base price of the order. 73 | * @param {boolean} hasDiscount - Indicates if the order has a discount. 74 | * @returns {number} The total price after applying tax and discount. 75 | */ 76 | function calculateTotalPrice(basePrice, hasDiscount) { 77 | const taxRate = 0.08; 78 | let discount = 0; 79 | if (hasDiscount) { 80 | discount = basePrice * 0.1; // 10% discount 81 | } 82 | return basePrice + (basePrice * taxRate) - discount; 83 | } 84 | ``` 85 | 86 | ### Bad Multi-Line Commenting Practice 87 | 88 | ```js 89 | /* 90 | This function calculates the price. 91 | It has parameters. 92 | It returns a number. 93 | */ 94 | function calculateTotalPrice(basePrice, hasDiscount) { 95 | // The actual function code 96 | } 97 | // Non-informative, redundant comments 98 | ``` 99 | 100 | ## Including Meaningful Comments & Avoiding Redundancy 101 | 102 | Strategic comments enhance code clarity, but beware of redundancy. Prioritize meaningful insights to facilitate collaboration and understanding among developers. 103 | 104 | ### Good Practice 105 | 106 | ```js 107 | // Loop through users and apply discounts to eligible ones 108 | users.forEach(user => { 109 | if (user.isEligibleForDiscount()) { 110 | applyDiscount(user); 111 | } 112 | }); 113 | ``` 114 | 115 | 116 | ```js 117 | // Calculate the area of a rectangle 118 | function calculateArea(length, width) { 119 | return length * width; 120 | } 121 | ``` 122 | 123 | ### Bad Practice 124 | 125 | ```js 126 | // Start a loop 127 | users.forEach(user => { 128 | // Check if the user is eligible for discount 129 | if (user.isEligibleForDiscount()) { 130 | // Apply discount to the user 131 | applyDiscount(user); 132 | } 133 | }); 134 | // Redundant comments that simply restate the code 135 | ``` 136 | 137 | ```js 138 | // Calculate area 139 | function calculateArea(l, w) { 140 | return l * w; 141 | // Ambiguous and unhelpful comment 142 | } 143 | ``` 144 | 145 | ## Indentation and Formatting 146 | 147 | Consistent indentation and formatting are crucial for readability. 148 | 149 | ### Good Practice 150 | 151 | Use consistent indentation (e.g., 2 or 4 spaces) and follow a style guide. 152 | 153 | ```js 154 | function exampleFunction() { 155 | if (condition) { 156 | // code 157 | } 158 | } 159 | ``` 160 | 161 | ### Bad Practice 162 | 163 | Mixing tabs and spaces or inconsistent indentation. 164 | 165 | ```js 166 | function exampleFunction() { 167 | if(condition){ 168 | // code 169 | } 170 | } 171 | // Inconsistent indentation 172 | ``` 173 | 174 | ## Consistent Formatting 175 | 176 | Adhering to a consistent code formatting style across your project is important. 177 | 178 | ### Good Practice 179 | 180 | Follow a formatting standard like Airbnb's JavaScript Style Guide or Google's JavaScript Style Guide. 181 | 182 | ### Bad Practice 183 | 184 | Inconsistent naming conventions, brace styles, or line breaks. 185 | 186 | --- 187 | 188 | Remember, the goal of these practices is to make your code as clear and maintainable as possible. Well-documented and formatted code not only benefits you but also your fellow developers who may work on your code in the future. 189 | -------------------------------------------------------------------------------- /resources/must-have-tools.mdx: -------------------------------------------------------------------------------- 1 | --- 2 | title: "Must-Have VS Code Extensions and Developer Tools" 3 | sidebarTitle: "VS Code & Tools" 4 | description: "A curated list of essential VS Code extensions and invaluable tools to boost the productivity and efficiency of developers." 5 | icon: "screwdriver-wrench" 6 | og:site_name: "Developer's Toolbox" 7 | og:title: "Must-Have VS Code Extensions and Developer Tools" 8 | og:description: "Discover essential VS Code extensions and tools that enhance productivity and efficiency in software development." 9 | og:url: "https://peacockindia.mintlify.app/resources/must-have-tools" 10 | og:image: "https://images.unsplash.com/photo-1473134090548-69219f9cbb80?q=80&w=3269&auto=format&fit=crop&ixlib=rb-4.0.3&ixid=M3wxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8fA%3D%3D" 11 | og:image:width: "1200" 12 | og:image:height: "630" 13 | og:locale: "en_US" 14 | article:publisher: "https://github.com/jacksonkasi1" 15 | twitter:title: "Must-Have VS Code Extensions and Developer Tools" 16 | twitter:description: "Essential VS Code extensions and tools for enhancing developer productivity." 17 | twitter:url: "https://peacockindia.mintlify.app/resources/must-have-tools" 18 | twitter:image: "https://images.unsplash.com/photo-1473134090548-69219f9cbb80?q=80&w=3269&auto=format&fit=crop&ixlib=rb-4.0.3&ixid=M3wxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8fA%3D%3D" 19 | twitter:site: "@jacksonkasi11" 20 | --- 21 | 22 | 23 | Using a Centralized Typography Component in React 28 | 29 | 30 | Visual Studio Code is a powerful editor that becomes even more versatile with extensions. This document lists essential extensions and tools that are highly recommended for developers looking to enhance their productivity. 31 | 32 | ## Visual Studio Code Extensions 33 | 34 | ### Code Formatting and Quality 35 | 36 | - **Prettier - Code formatter** 37 | 38 | - [Prettier Extension](https://marketplace.visualstudio.com/items?itemName=esbenp.prettier-vscode) 39 | 40 | - **ESLint** 41 | 42 | - [ESLint Extension](https://marketplace.visualstudio.com/items?itemName=dbaeumer.vscode-eslint) 43 | 44 | - **Code Spell Checker** 45 | - [Code Spell Checker](https://marketplace.visualstudio.com/items?itemName=streetsidesoftware.code-spell-checker) 46 | 47 | ### Git Integration 48 | 49 | - **GitLens** 50 | - [GitLens Extension](https://marketplace.visualstudio.com/items?itemName=eamodio.gitlens) 51 | 52 | ### Code Navigation and Efficiency 53 | 54 | - **Bracket Pair Colorizer** 55 | 56 | - [Bracket Pair Colorizer](https://marketplace.visualstudio.com/items?itemName=CoenraadS.bracket-pair-colorizer-2) 57 | 58 | - **Bookmarks** 59 | 60 | - [Bookmarks Extension](https://marketplace.visualstudio.com/items?itemName=alefragnani.Bookmarks) 61 | 62 | - **Path Intellisense** 63 | - [Path Intellisense](https://marketplace.visualstudio.com/items?itemName=christian-kohler.path-intellisense) 64 | 65 | ### Development Utilities 66 | 67 | - **Live Server** 68 | 69 | - [Live Server Extension](https://marketplace.visualstudio.com/items?itemName=ritwickdey.LiveServer) 70 | 71 | - **Better Comments** 72 | 73 | - [Better Comments](https://marketplace.visualstudio.com/items?itemName=aaron-bond.better-comments) 74 | 75 | - **Error Lens** 76 | 77 | - [Error Lens](https://marketplace.visualstudio.com/items?itemName=usernamehw.errorlens) 78 | 79 | - **ES7 React/Redux/GraphQL/React-Native Snippets** 80 | - [ES7 React JS Snippets](https://marketplace.visualstudio.com/items?itemName=dsznajder.es7-react-js-snippets) 81 | 82 | ### Styling and CSS 83 | 84 | - **Bootstrap Class Autocomplete** 85 | 86 | - [Bootstrap Class Autocomplete](https://marketplace.visualstudio.com/items?itemName=torresgol10.bootstrap-class-autocomplete) 87 | 88 | - **Tailwind CSS IntelliSense** 89 | - [Tailwind CSS IntelliSense](https://marketplace.visualstudio.com/items?itemName=bradlc.vscode-tailwindcss) 90 | 91 | ### Testing and Performance 92 | 93 | - **Wallaby.js** 94 | - [Wallaby.js](https://marketplace.visualstudio.com/items?itemName=WallabyJs.wallaby-vscode) 95 | 96 | --- 97 | 98 | ## Useful Tools for Developers 99 | 100 | A developer's toolkit can be vast and varied, depending on their specific needs and workflow. Here's a list of tools that come highly recommended for boosting productivity and streamlining processes. 101 | 102 | - **Postman** 103 | 104 | - An API development environment used for making HTTP requests, testing, and API management. 105 | - [Postman](https://www.postman.com/) 106 | 107 | - **Figma** 108 | 109 | - A vector graphics editor and prototyping tool for designing user interfaces. 110 | - [Figma](https://www.figma.com/) 111 | 112 | - **Notion** 113 | 114 | - An all-in-one workspace for note-taking, project management, and task organization. 115 | - [Notion](https://www.notion.so/) 116 | 117 | - **Canva** 118 | 119 | - A graphic design platform used to create social media graphics, presentations, posters, and other visual content. 120 | - [Canva](https://www.canva.com/) 121 | 122 | - **ClickUp** 123 | 124 | - A cloud-based collaboration and project management tool suited for businesses of all sizes and industries. 125 | - [ClickUp](https://clickup.com) 126 | 127 | - **Daily.dev** 128 | 129 | - A tool that aggregates and ranks articles from the tech world to keep you updated with the latest news. 130 | - [Daily.dev](https://app.daily.dev/) 131 | 132 | - **Nozbe** 133 | 134 | - A task, project, and time management application that helps individuals and teams organize their work. 135 | - [Nozbe](https://nozbe.com/) 136 | 137 | - **Napkin.ai** 138 | 139 | - A tool for quickly jotting down ideas and concepts, akin to using a napkin for sketches and notes. 140 | - [Napkin.ai](https://napkin.ai/) 141 | 142 | - **Flameshot** 143 | 144 | - A powerful yet simple-to-use screenshot software. 145 | - [Flameshot](https://flameshot.org/) 146 | 147 | - **MeasureMate** 148 | 149 | - A tool for measuring screen dimensions, perfect for designers and developers focusing on responsive design. 150 | - [MeasureMate](https://measuremate.xyz/) 151 | 152 | - **Mobile Simulator - Responsive Testing Tool** 153 | 154 | - A web-based tool to simulate mobile devices for responsive testing. 155 | - [WebMobileFirst](https://www.webmobilefirst.com/en/) 156 | 157 | - **NormCap** 158 | 159 | - An OCR tool that captures text from any part of your screen and makes it editable. 160 | - [NormCap](https://dynobo.github.io/normcap/) 161 | 162 | - **GitHub Web IDE** 163 | 164 | - A Chrome extension that turns your GitHub repository into a web-based Visual Studio Code environment. 165 | - [Chrome Extension](https://chrome.google.com/webstore/detail/adjiklnjodbiaioggfpbpkhbfcnhgkfe) 166 | - [GitHub Web IDE](https://github.com/zvizvi/GitHub-Web-IDE) 167 | 168 | - **UniJump - Shortcut for ChatGPT** 169 | - This Chrome extension provides quick access shortcuts to OpenAI's ChatGPT. 170 | - [UniJump for ChatGPT](https://chrome.google.com/webstore/detail/olikadnicfhhpkfleolncoligkdcmjai) 171 | 172 | --- 173 | 174 | 175 | If you have suggestions for indispensable tools that fellow developers should 176 | know about, please share them so we can continue to build this resource 177 | together. 178 | 179 | 180 | ## Conclusion 181 | 182 | The right set of VS Code extensions and tools can significantly streamline and refine your development process. As you incorporate these selections into your practice, they'll enhance not just your productivity, but also the caliber of your work. 183 | -------------------------------------------------------------------------------- /docs/code-optimization.mdx: -------------------------------------------------------------------------------- 1 | --- 2 | title: "Optimizing Code Logic in JavaScript and TypeScript" 3 | sidebarTitle: "Code Optimization" 4 | description: "Discover strategies for streamlining code execution through best practices in JavaScript and TypeScript, including examples of recursion and algorithm optimization." 5 | icon: "gauge" 6 | og:site_name: "Advanced Coding Techniques" 7 | og:title: "Optimizing Code Logic in JavaScript and TypeScript" 8 | og:description: "Learn how to refine your JavaScript and TypeScript code for better performance and efficiency." 9 | og:url: "https://peacockindia.mintlify.app/docs/code-optimization" 10 | og:image: "https://images.unsplash.com/photo-1475598322381-f1b499717dda?q=80&w=3276&auto=format&fit=crop&ixlib=rb-4.0.3&ixid=M3wxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8fA%3D%3D" 11 | og:image:width: "1200" 12 | og:image:height: "630" 13 | og:locale: "en_US" 14 | article:publisher: "https://github.com/jacksonkasi1" 15 | twitter:title: "Optimizing Code Logic in JavaScript and TypeScript" 16 | twitter:description: "Explore best practices and strategies for enhancing code performance in JavaScript and TypeScript." 17 | twitter:url: "https://peacockindia.mintlify.app/docs/code-optimization" 18 | twitter:image: "https://images.unsplash.com/photo-1475598322381-f1b499717dda?q=80&w=3276&auto=format&fit=crop&ixlib=rb-4.0.3&ixid=M3wxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8fA%3D%3D" 19 | twitter:site: "@jacksonkasi11" 20 | --- 21 | 22 | 23 | Best Practices for Import Statements in React 28 | 29 | 30 | 31 | Efficient code is not only about what it does but also how fast and resource-effectively it does it. This document explores best practices for writing efficient JavaScript and TypeScript code, touching upon recursive functions, algorithm choice, and optimization techniques. 32 | 33 | ## Efficient Function Execution 34 | 35 | ### Good Example: Efficient Function 36 | 37 | ```typescript 38 | function quickSort(data: number[]): number[] { 39 | // Efficient sorting logic 40 | } 41 | ``` 42 | 43 | ### Bad Example: Inefficient Function 44 | 45 | ```typescript 46 | function slowSort(data: number[]): number[] { 47 | // Inefficient sorting logic with unnecessary complexity 48 | } 49 | ``` 50 | 51 | --- 52 | 53 | In the context of code efficiency and best practices, the two provided functions demonstrate how different approaches to a similar problem can affect readability and maintainability: 54 | 55 | ### Good Example: Using a Mapping Object 56 | 57 | ```typescript 58 | type IconFillColor = "primary" | "secondary"; 59 | 60 | const iconFillColors: Record = { 61 | "primary": "#000000", 62 | "secondary": "#808080", 63 | }; 64 | 65 | export function getIconFillColor(fillColor: IconFillColor) { 66 | return iconFillColors[fillColor] ?? throw new Error(`Invalid fill color: ${fillColor}`); 67 | } 68 | ``` 69 | 70 | ### Bad Example: Using a Switch Statement 71 | 72 | ```typescript 73 | type IconFillColor = "primary" | "secondary"; 74 | 75 | export function getIconFillColor(fillColor: IconFillColor) { 76 | switch (fillColor) { 77 | case "primary": 78 | return "#000000"; 79 | case "secondary": 80 | return "#808080"; 81 | default: 82 | throw new Error(`Invalid fill color: ${fillColor}`); 83 | } 84 | } 85 | ``` 86 | 87 | The "good" example uses a mapping object which is more succinct and easier to manage, especially when dealing with a large number of cases. It avoids the boilerplate of a `switch` statement and makes the function shorter and cleaner. 88 | 89 | --- 90 | 91 | ## Simplifying Complex Logic with Design Patterns 💥 92 | 93 | Certainly, using multiple `if` conditions can make code hard to read and maintain. A better approach might be to encapsulate each condition in its own function or use a strategy pattern. Here's a comparison: 94 | 95 | ### Bad Example: Multiple If Conditions 96 | 97 | ```javascript 98 | function processRequest(type) { 99 | if (type === "create") { 100 | // create logic 101 | } else if (type === "update") { 102 | // update logic 103 | } else if (type === "delete") { 104 | // delete logic 105 | } 106 | // ...more conditions... 107 | } 108 | ``` 109 | 110 | ### Good Example: Strategy Pattern with Functions 111 | 112 | ```javascript 113 | const operations = { 114 | create: (data) => { 115 | // create logic 116 | }, 117 | update: (data) => { 118 | // update logic 119 | }, 120 | delete: (data) => { 121 | // delete logic 122 | }, 123 | // ...more operations... 124 | }; 125 | 126 | function processRequest(type, data) { 127 | const operation = operations[type]; 128 | if (operation) { 129 | operation(data); 130 | } else { 131 | throw new Error("Invalid operation type"); 132 | } 133 | } 134 | ``` 135 | 136 | In the "good" example, each operation is encapsulated in its own function within a `operations` object. This not only makes the `processRequest` function cleaner but also simplifies adding or modifying operations in the future. 137 | 138 | > This is just one way to approach the problem. Other design patterns can also be used to simplify complex logic. 139 | 140 | 141 | ## Tips for Writing Efficient TypeScript Code 142 | 143 | Leverage TypeScript’s type system for performance and safety. 144 | 145 | ### Good Example: Leveraging TypeScript’s Types for Performance 146 | 147 | ```typescript 148 | interface Comparable { 149 | compareTo(other: Comparable): number; 150 | } 151 | 152 | // Implementing an efficient sorting algorithm using the Comparable interface 153 | ``` 154 | 155 | ### Bad Example: Ignoring TypeScript’s Type System 156 | 157 | ```typescript 158 | // Using 'any' type reduces the ability to optimize and can lead to runtime errors 159 | function sortItems(items: any[]): any[] { 160 | // Sorting logic without type checks 161 | } 162 | ``` 163 | 164 | ## Recursive Functions and Performance 165 | 166 | Recursion can be elegant but sometimes comes at the cost of performance. 167 | 168 | ### Good Example: Tail-Recursive Optimization 169 | 170 | ```javascript 171 | function factorial(n, accumulator = 1) { 172 | if (n === 0) { 173 | return accumulator; 174 | } 175 | return factorial(n - 1, n * accumulator); 176 | } 177 | ``` 178 | 179 | ### Bad Example: Non-Optimized Recursive Function 180 | 181 | ```javascript 182 | function factorial(n) { 183 | if (n === 1) { 184 | return 1; 185 | } 186 | return n * factorial(n - 1); // Potential stack overflow for large n 187 | } 188 | ``` 189 | 190 | ## Choosing the Right Algorithm 191 | 192 | The efficiency of an algorithm significantly impacts performance, especially with large datasets. 193 | 194 | ### Good Example: Efficient Algorithm Selection 195 | 196 | ```typescript 197 | // Binary search for sorted arrays 198 | function binarySearch(array: number[], target: number): boolean { 199 | // Binary search logic 200 | } 201 | ``` 202 | 203 | ### Bad Example: Inefficient Algorithm Selection 204 | 205 | ```typescript 206 | // Linear search on a sorted array is less efficient 207 | function linearSearch(array: number[], target: number): boolean { 208 | // Linear search logic 209 | } 210 | ``` 211 | 212 | ## Conclusion 213 | 214 | Embracing efficient coding practices in JavaScript and TypeScript not only streamlines your development process but also enhances the performance and maintainability of your applications. By utilizing design patterns, optimizing algorithms, and employing the power of TypeScript's type system, you can write cleaner, more effective code. Always strive to balance clarity with performance, and remember that the best code is not only functional but also intuitive and accessible to other developers in the long term. 215 | -------------------------------------------------------------------------------- /logo/light.svg: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /logo/dark.svg: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /docs/react-code-structure.mdx: -------------------------------------------------------------------------------- 1 | --- 2 | title: "Efficient Code Structure in React Components" 3 | sidebarTitle: "React Code Structure" 4 | description: "A guide to organizing code within React components for maximum efficiency and readability, including best practices and common pitfalls." 5 | icon: "react" 6 | og:site_name: "React Best Practices" 7 | og:title: "Efficient Code Structure in React Components" 8 | og:description: "Delve into the strategies for structuring code in React components to enhance efficiency and readability." 9 | og:url: "https://peacockindia.mintlify.app/docs/react-code-structure" 10 | og:image: "https://images.unsplash.com/photo-1476514525535-07fb3b4ae5f1?q=80&w=3270&auto=format&fit=crop&ixlib=rb-4.0.3&ixid=M3wxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8fA%3D%3D" 11 | og:image:width: "1200" 12 | og:image:height: "630" 13 | og:locale: "en_US" 14 | article:publisher: "https://github.com/jacksonkasi1" 15 | twitter:title: "Efficient Code Structure in React Components" 16 | twitter:description: "Discover the keys to effective React component structuring for better maintainability and performance." 17 | twitter:url: "https://peacockindia.mintlify.app/docs/react-code-structure" 18 | twitter:image: "https://images.unsplash.com/photo-1476514525535-07fb3b4ae5f1?q=80&w=3270&auto=format&fit=crop&ixlib=rb-4.0.3&ixid=M3wxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8fA%3D%3D" 19 | twitter:site: "@jacksonkasi11" 20 | --- 21 | 22 | 23 | Efficient Code Structure in React Components 28 | 29 | 30 | Organizing code within React components in a logical and efficient manner is crucial for readability and maintainability. This guide outlines the recommended order and structure for various elements within a React component. 31 | 32 | ## Recommended Structure Inside React Components 33 | 34 | 1. **Variables and Constants**: Declare any constants or variables at the beginning of the component. 35 | 36 | ```jsx 37 | const LIMIT = 10; 38 | ``` 39 | 40 | 2. **State Management & other hooks (Redux, Context)**: Initialize Redux hooks or Context API hooks next. 41 | 42 | ```jsx 43 | const user = useSelector(state => state.user); 44 | ``` 45 | 46 | 3. **Local State (useState, useReducer)**: Define local state hooks after state management hooks. 47 | 48 | ```jsx 49 | const [count, setCount] = useState(0); 50 | ``` 51 | 52 | 4. **Effects (useEffect)**: Place `useEffect` hooks after state declarations to capture component lifecycle events. 53 | 54 | ```jsx 55 | useEffect(() => { 56 | loadData(); 57 | }, [dependency]); 58 | ``` 59 | 60 | 5. **Event Handlers and Functions**: Define event handlers and other functions after hooks. 61 | 62 | ```jsx 63 | const handleIncrement = () => { 64 | setCount(prevCount => prevCount + 1); 65 | }; 66 | ``` 67 | 68 | ### Example of good structure ✅ 69 | 70 | ```jsx 71 | import React, { useState, useEffect } from 'react'; 72 | import { useSelector } from 'react-redux'; 73 | import SomeService from './SomeService'; 74 | import './Page.css'; 75 | 76 | const Page = ({ variant, ...props }) => { 77 | // Constants 78 | const MAX_COUNT = 10; 79 | 80 | // Redux State 81 | const user = useSelector(state => state.user); 82 | 83 | // Local State 84 | const [count, setCount] = useState(0); 85 | const [data, setData] = useState(null); 86 | 87 | // useEffect for loading data 88 | useEffect(() => { 89 | SomeService.getData().then(data => setData(data)); 90 | }, []); 91 | 92 | // useEffect for user-related operations 93 | useEffect(() => { 94 | if (user) { 95 | console.log('User updated:', user); 96 | } 97 | }, [user]); 98 | 99 | // Event Handlers 100 | const handleIncrement = () => { 101 | if (count < MAX_COUNT) { 102 | setCount(prevCount => prevCount + 1); 103 | } 104 | }; 105 | 106 | return ( 107 |
108 |

Welcome, {user.name}

109 | 110 |

Count: {count}

111 | {data &&
Data loaded!
} 112 |
113 | ); 114 | }; 115 | 116 | export default Page; 117 | ``` 118 | 119 | In this example, the structure of the React component follows a logical order: 120 | 121 | 1. **Imports**: Grouped at the top, starting with React-related imports, followed by Redux hooks, services, and styles. 122 | 2. **Component Function**: The functional component `Page` starts with constants, followed by state management using Redux, local state with `useState`, lifecycle methods with `useEffect`, and event handler functions. 123 | 3. **Return Statement**: The JSX returned by the component is clearly structured at the end. 124 | 125 | This organization makes the code more readable and maintainable, especially as components grow in complexity. 126 | 127 | 128 | ## Bad Practices to Avoid 129 | 130 | - **Mixing Hook Types**: Avoid interleaving useState, useEffect, and custom hooks randomly. This can lead to confusion and makes the code less predictable. 131 | 132 | - **Declaring Functions or Variables in the Middle of Hooks**: Inserting function or variable declarations amidst hook calls disrupts the flow and readability. 133 | 134 | - **Multiple useEffect Calls with Similar Dependencies**: Consolidate effects with similar dependencies to avoid unnecessary re-renders and side effects. 135 | 136 | ### Example of Poor Structure 📛 137 | 138 | ```jsx 139 | const [name, setName] = useState(''); 140 | const handleNameChange = (e) => setName(e.target.value); 141 | 142 | const [age, setAge] = useState(0); 143 | // ... other code ... 144 | 145 | useEffect(() => { 146 | validateName(name); 147 | }, [name]); 148 | 149 | const LIMIT = 5; 150 | // ... other code ... 151 | 152 | useEffect(() => { 153 | // Another effect with the same dependency 154 | }, [name]); 155 | ``` 156 | 157 | This example demonstrates inefficient organization with useState and useEffect hooks scattered throughout the component, making it hard to track the component's logic and lifecycle. 158 | 159 | --- 160 | 161 | 162 | ## Flexible Structure with Custom Hooks 163 | 164 | While a standard order for hooks and variables is typically recommended, certain scenarios, particularly involving custom hooks, may require a more adaptable approach. 165 | 166 | Balancing Structure with Practical Needs 167 | 168 | In real-world development, the ideal order of hooks might be adjusted to suit specific functional requirements or dependencies. This is especially true with custom hooks that depend on state or other hooks. 169 | 170 | #### Example: Adjusting Order for Custom Hooks and useState 💡 171 | 172 | Consider a scenario where a custom hook's output is used as a dependency in another hook or a piece of state. Here, the order of `useState` and the custom hook may be interchanged for functional necessity. 173 | 174 | ```jsx 175 | import React, { useState } from 'react'; 176 | import useGetAllMenuItems from './useGetAllMenuItems'; 177 | import useUUID from './useUUID'; 178 | 179 | const MenuComponent = ({ restaurant_id, tbl_id, limit }) => { 180 | // Custom hook that needs to precede certain state hooks 181 | const uuid = useUUID(); 182 | 183 | // useState hooks, some of which depend on the custom hook's output 184 | const [searchQuery, setSearchQuery] = useState(''); 185 | const [sortby, setSortby] = useState('rating'); 186 | const [category, setCategory] = useState(''); 187 | 188 | // Another custom hook that uses state and the output from useUUID 189 | const { data: menuItems, error } = useGetAllMenuItems( 190 | restaurant_id, 191 | uuid, 192 | tbl_id, 193 | limit, 194 | searchQuery, 195 | sortby, 196 | category, 197 | ); 198 | 199 | // Component logic and JSX 200 | return ( 201 | // JSX rendering using menuItems 202 | ); 203 | }; 204 | 205 | export default MenuComponent; 206 | ``` 207 | 208 | In this example, `useUUID` is called before certain `useState` hooks because its output is required by `useGetAllMenuItems`. This demonstrates the need for flexibility in structuring components. 209 | 210 | Note: This is just one of the example with API hooks & useState. Based on your case it maybe change. 211 | 212 | This section emphasizes the importance of adaptability in structuring React components, especially when using custom hooks that have dependencies on other state or hooks. It serves as a practical extension to the initial guide, acknowledging the nuances of real-world React development. 213 | 214 | ## Conclusion 215 | 216 | A well-structured React component enhances the developer's ability to understand and maintain the code. Following these guidelines ensures that your components are organized logically, which is especially crucial in larger applications where the complexity can escalate quickly. Remember, consistency in code structure not only benefits you but also your teammates who work on the codebase. 217 | -------------------------------------------------------------------------------- /docs/organizing-imports.mdx: -------------------------------------------------------------------------------- 1 | --- 2 | title: "Best Practices for Import Statements in React" 3 | sidebarTitle: "Organizing Imports" 4 | description: "Learn about the optimal order and style for importing modules in React projects." 5 | icon: "cubes" 6 | og:site_name: "React Development Insights" 7 | og:title: "Best Practices for Import Statements in React" 8 | og:description: "Discover efficient techniques for organizing and structuring import statements in React applications." 9 | og:url: "https://peacockindia.mintlify.app/docs/organizing-imports" 10 | og:image: "https://images.unsplash.com/photo-1497436072909-60f360e1d4b1?q=80&w=2560&auto=format&fit=crop&ixlib=rb-4.0.3&ixid=M3wxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8fA%3D%3D" 11 | og:image:width: "1200" 12 | og:image:height: "630" 13 | og:locale: "en_US" 14 | article:publisher: "https://github.com/jacksonkasi1" 15 | twitter:title: "Best Practices for Import Statements in React" 16 | twitter:description: "Enhance the readability and maintainability of your React code with organized import statements." 17 | twitter:url: "https://peacockindia.mintlify.app/docs/organizing-imports" 18 | twitter:image: "https://images.unsplash.com/photo-1497436072909-60f360e1d4b1?q=80&w=2560&auto=format&fit=crop&ixlib=rb-4.0.3&ixid=M3wxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8fA%3D%3D" 19 | twitter:site: "@jacksonkasi11" 20 | --- 21 | 22 | 23 | Best Practices for Import Statements in React 28 | 29 | 30 | ## Best Practices for Import Statements in React 31 | 32 | Understanding and maintaining a consistent order for import statements in React applications can greatly improve code readability and maintainability. Here's a guideline on how to structure your import statements for clarity and efficiency. 33 | 34 | 35 | This is not a programing style guide. It's a guideline on how to organize your 36 | imports. 37 | 38 | 39 | ### Core Packages 40 | 41 | Always start by importing core packages. These are essential libraries that your project depends on. 42 | 43 | ```js 44 | import React, { useEffect } from "react"; 45 | import { useNavigate } from "react-router-dom"; 46 | ``` 47 | 48 | ### Assets 49 | 50 | Next, import assets like images, SVGs, and icons. Grouping these together helps in identifying resource dependencies at a glance. 51 | 52 | ```js 53 | // ** import icons 54 | import BackSvg from "@icons/BackSvg"; 55 | import SearchSvg from "@icons/SearchSvg"; 56 | 57 | // ** import assets 58 | import googleSvg from "@svg/google.svg"; 59 | import AbsoluteLogo from "@svg/AbsoluteLogo.svg"; 60 | import frontGirl from "@illustration/FrontGirl.svg"; 61 | import userImage from "@illustration/userImage.webp"; 62 | ``` 63 | 64 | ### Third-Party Packages 65 | 66 | After assets, bring in third-party packages. These are external libraries that are not part of the core packages. 67 | 68 | ```js 69 | // ** import third party 70 | import { toast } from "react-toastify"; 71 | import { CircularProgress } from "@nextui-org/react"; 72 | ``` 73 | 74 | ### Shared Components 75 | 76 | Shared components are reusable components used across different parts of your application. 77 | 78 | ```js 79 | // ** import shared components 80 | import Image from "@shared/Image"; 81 | import Button from "@shared/Button"; 82 | import Typography from "@shared/Typography"; 83 | ``` 84 | 85 | ### Components 86 | 87 | Following shared components, import specific components that are used in your current module. 88 | 89 | ```js 90 | // ** import components 91 | import AddFoodItem from "@components/AddFoodItem"; 92 | import CalendarPopup from "@components/CalendarPopup"; 93 | ``` 94 | 95 | ### Sub Pages/Sections 96 | 97 | Sub-pages or section imports come next. These are often specific to the module you're working on. 98 | 99 | ```js 100 | // ** import sub pages/sections 101 | import Section1 from "./Section1"; 102 | import Section2 from "./Section2"; 103 | import Section3 from "./Section3"; 104 | ``` 105 | 106 | ### Configuration Files 107 | 108 | Configuration files like environment settings should be imported thereafter. 109 | 110 | ```js 111 | // ** import config 112 | import env from "@src/config"; 113 | ``` 114 | 115 | ### State Management 116 | 117 | For state management tools (like Redux), import them after your configuration files. 118 | 119 | ```js 120 | // ** import state manager 121 | import { useDispatch } from "react-redux"; 122 | import { setLocale } from "@src/redux/slices/language"; 123 | ``` 124 | 125 | ### Utilities and Libraries 126 | 127 | Utility functions or libraries are imported next. They usually provide helper functions used across components. 128 | 129 | ```js 130 | // ** import utils 131 | import { useStorableState } from "@utils/useStorable"; 132 | ``` 133 | 134 | ### Custom Hooks 135 | 136 | Custom hooks, which encapsulate logic, are imported following utilities. 137 | 138 | ```js 139 | // ** import hooks 140 | import useStorable from "@src/utils/useStorable"; 141 | ``` 142 | 143 | ### APIs 144 | 145 | Finally, import your API functions or services. This keeps API-related imports organized and easily identifiable. 146 | 147 | ```js 148 | // ** import apis 149 | import { getUserProfileApi } from "@api/auth"; 150 | import { confirmOrderApi } from "@api/cart"; 151 | ``` 152 | 153 | 154 | In simple terms, here is the overall order of imports style guide: 155 | 156 | 1) core packages (e.g. React, React Router, Next, etc...) 157 | 2) assets (e.g. images, SVGs, icons, etc...) 158 | 3) component/shared ui/sub pages 159 | 4) third-party packages 160 | 5) configuration files/utils/types/validation schema/hooks/custom hooks/sate management 161 | 6) api functions/services 162 | 163 | 164 | ## Example `index.js` 165 | 166 | Click on the following dropdown to view a sample `index.js` file with imports organized according to the order described above. 167 | 168 | 169 | 170 | ```js index.js 171 | import React, { useEffect } from "react"; 172 | import { useNavigate } from "react-router-dom"; 173 | 174 | // ** import icons 175 | import BackSvg from "@icons/BackSvg"; 176 | import SearchSvg from "@icons/SearchSvg"; 177 | 178 | // ** import assets 179 | import googleSvg from "@svg/google.svg"; 180 | import AbsoluteLogo from "@svg/AbsoluteLogo.svg"; 181 | import frontGirl from "@illustration/FrontGirl.svg"; 182 | import userImage from "@illustration/userImage.webp"; 183 | 184 | // ** import third party 185 | import { toast } from "react-toastify"; 186 | import { CircularProgress } from "@nextui-org/react"; 187 | 188 | // ** import shared components 189 | import Image from "@shared/Image"; 190 | import Button from "@shared/Button"; 191 | import Typography from "@shared/Typography"; 192 | 193 | // ** import components 194 | import AddFoodItem from "@components/AddFoodItem"; 195 | import CalendarPopup from "@components/CalendarPopup"; 196 | 197 | // ** import sub pages/sections 198 | import Section1 from "./Section1"; 199 | import Section2 from "./Section2"; 200 | import Section3 from "./Section3"; 201 | 202 | // ** import config 203 | import env from "@src/config"; 204 | 205 | // ** import state manager 206 | import { useDispatch } from "react-redux"; 207 | import { setLocale } from "@src/redux/slices/language"; 208 | 209 | // ** import utils 210 | import { useStorableState } from "@utils/useStorable"; 211 | 212 | // ** import hooks 213 | import useStorable from "@src/utils/useStorable"; 214 | 215 | // ** import apis 216 | import { getUserProfileApi } from "@api/auth"; 217 | import { confirmOrderApi } from "@api/cart"; 218 | ``` 219 | 220 | 221 | 222 | ## Import Aliases 223 | 224 | Import aliases simplify import statements, making them more readable and manageable, especially in large projects. Here's how to use them effectively in Node.js, React, and Next.js 14. 225 | 226 | ### Good Practice: Using Import Aliases 227 | 228 | ```javascript 229 | // In a React/Next.js project 230 | import Button from '@components/Button'; 231 | 232 | // In a Node.js project 233 | const dbConfig = require('@config/db'); 234 | ``` 235 | 236 | ### Bad Practice: Without Import Aliases 237 | 238 | ```javascript 239 | // Complex and lengthy relative paths 240 | import Button from '../../../components/Button'; 241 | const dbConfig = require('../../config/db'); 242 | ``` 243 | 244 | ### Setting Up Aliases 245 | 246 | - **React/Next.js**: Configure `jsconfig.json` or `tsconfig.json` for alias paths. 247 | - **Node.js**: Use `module-alias` package or configure `package.json` for custom paths. 248 | 249 | Import aliases streamline project structure by reducing the complexity of import statements, enhancing code readability and maintainability. 250 | 251 | --- 252 | 253 | **References:** 254 | - [Using Import Aliases in JavaScript](https://medium.com/dailyjs/using-import-aliases-in-javascript-a0b46237601c) 255 | - [module-alias Package](https://www.npmjs.com/package/module-alias) 256 | - [Configuring Path Aliases in Frontend Projects](https://betterprogramming.pub/the-native-way-to-configure-path-aliases-in-frontend-projects-5db70f19a6e0) 257 | 258 | By following this order, your imports will be neatly organized and easily understandable to anyone reading your code. This not only aids in development but also in maintaining the codebase efficiently. 259 | -------------------------------------------------------------------------------- /images/hero-light.svg: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /docs/secure-coding.mdx: -------------------------------------------------------------------------------- 1 | --- 2 | title: "Secure Coding Practices in Web Development" 3 | sidebarTitle: "Secure Coding" 4 | description: "Learn how to write secure code to protect web applications from common vulnerabilities, with examples of dos and don'ts." 5 | icon: "shield" 6 | og:site_name: "Web Security Essentials" 7 | og:title: "Secure Coding Practices in Web Development" 8 | og:description: "A comprehensive guide to implementing secure coding practices in web development, covering common security vulnerabilities." 9 | og:url: "https://peacockindia.mintlify.app/docs/secure-coding" 10 | og:image: "https://images.unsplash.com/photo-1451337516015-6b6e9a44a8a3?q=80&w=3174&auto=format&fit=crop&ixlib=rb-4.0.3&ixid=M3wxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8fA%3D%3D" 11 | og:image:width: "1200" 12 | og:image:height: "630" 13 | og:locale: "en_US" 14 | article:publisher: "https://github.com/jacksonkasi1" 15 | twitter:title: "Secure Coding Practices in Web Development" 16 | twitter:description: "Essential practices for writing secure code in web development, preventing vulnerabilities and enhancing security." 17 | twitter:url: "https://peacockindia.mintlify.app/docs/secure-coding" 18 | twitter:image: "https://images.unsplash.com/photo-1451337516015-6b6e9a44a8a3?q=80&w=3174&auto=format&fit=crop&ixlib=rb-4.0.3&ixid=M3wxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8fA%3D%3D" 19 | twitter:site: "@jacksonkasi11" 20 | --- 21 | 22 | 23 | Secure Coding Practices in Web Development 28 | 29 | 30 | Security is a paramount aspect of web development. Writing secure code is crucial to protect against vulnerabilities like SQL injection, XSS (Cross-Site Scripting), and CSRF (Cross-Site Request Forgery). This document outlines best practices for writing secure code along with examples. 31 | 32 | ## Preventing SQL Injection 💉 33 | 34 | ### Vulnerable Code Example 35 | 36 | ```javascript 37 | // Using string concatenation in SQL queries 38 | const query = `SELECT * FROM users WHERE username = '${username}' AND password = '${password}'`; 39 | ``` 40 | 41 | ### Secure Code Example 42 | 43 | ```javascript 44 | // Using parameterized queries 45 | const query = `SELECT * FROM users WHERE username = ? AND password = ?`; 46 | db.query(query, [username, password]); 47 | ``` 48 | 49 | ## Protecting Against XSS Attacks 🛡️ 50 | 51 | #### Understanding the Risk 52 | 53 | Cross-Site Scripting (XSS) attacks occur when malicious scripts are injected into webpages viewed by other users. This can lead to data theft, session hijacking, and other security breaches. 54 | 55 | [To learn more about XSS ↗️](https://www.esecurityplanet.com/endpoint/prevent-xss-attacks) 56 | 57 | ### Vulnerable Code Example 58 | 59 | ```javascript 60 | // Rendering user input directly to the DOM 61 | document.getElementById("user-content").innerHTML = userInput; 62 | ``` 63 | 64 | ### Secure Code Example 65 | 66 | ```javascript 67 | // Escaping user input before rendering 68 | const safeInput = escapeHtml(userInput); 69 | document.getElementById("user-content").textContent = safeInput; 70 | ``` 71 | 72 | ```javascript 73 | // Example: Using DOMPurify to sanitize user input 74 | const cleanInput = DOMPurify.sanitize(userInput); 75 | document.getElementById("user-content").innerHTML = cleanInput; 76 | ``` 77 | 78 | ## Mitigating CSRF Attacks 🛡️ 79 | 80 | #### Understanding the Risk 81 | 82 | CSRF attacks force a logged-on victim to submit a request to a web application on which they are currently authenticated. These attacks can be used to perform actions on behalf of the user without their consent. 83 | 84 | [To learn more about CSRF ↗️](https://cheatsheetseries.owasp.org/cheatsheets/Cross-Site_Request_Forgery_Prevention_Cheat_Sheet.html) 85 | 86 | ### Vulnerable Code Example 87 | 88 | ```html 89 | 90 | Delete Account 91 | ``` 92 | 93 | ### Secure Code Example 94 | 95 | **Mitigating CSRF Attacks** 96 | 97 | ```javascript 98 | // Backend: Generate and validate CSRF tokens 99 | app.use(csrfProtection); 100 | app.post("/delete-account", (req, res) => { 101 | // Validate CSRF token 102 | }); 103 | ``` 104 | 105 | ```html 106 | 107 |
108 | 109 | 110 |
111 | ``` 112 | 113 | [know more](https://brightsec.com/blog/csrf-token) 114 | 115 | These sections provide an understanding of XSS and CSRF risks, along with practical code examples and links for further reading, enhancing the security knowledge of developers. 116 | 117 | ## Handling Vulnerable Dependencies 🐞 118 | 119 | ### Using npm-audit to Identify Vulnerabilities 120 | 121 | Run `npm audit` to identify and fix insecure dependencies. Regularly update your packages to the latest, non-vulnerable versions. 122 | 123 | ### Incorporating Snyk for Continuous Security 124 | 125 | Integrate [Snyk](https://snyk.io/) into your development workflow for continuous monitoring and fixing of vulnerabilities in dependencies. 126 | 127 | ## Managing Environment Variables Securely 🔐 128 | 129 | ### Storing Secrets in `.env` Files 130 | 131 | Store sensitive information like API keys and passwords in `.env` files and access them via `process.env` in your code. 132 | 133 | **Bad Practice: Hardcoding secrets in code** 134 | 135 | ```js 136 | // Bad Practice: Hardcoded secret 137 | const API_KEY = "hardcoded-secret-key"; 138 | ``` 139 | 140 | **Good Practice: Storing secret in .env file** 141 | 142 | ```js 143 | // Example of accessing a secret from .env file 144 | require("dotenv").config(); 145 | const API_KEY = process.env.API_KEY; 146 | ``` 147 | 148 | ### Using Secure Storage for Environment Secrets 149 | 150 | For higher security, especially in production, use services like [1Password](https://1password.com/developers) or [Phase](https://phase.dev/). These services securely manage and inject secrets into your application. 151 | 152 | **Example: Integrating 1Password** 153 | 154 | ```javascript 155 | // Assuming you have 1Password CLI set up and secrets synced 156 | const { op } = require("1password"); 157 | (async () => { 158 | const apiKey = await op.getItem("API_KEY"); 159 | process.env.API_KEY = apiKey; 160 | })(); 161 | ``` 162 | 163 | In this example, the 1Password CLI is used to securely fetch the API key and set it as an environment variable. This method enhances security by avoiding hardcoded secrets in your codebase or `.env` files. 164 | 165 | [To learn more ↗️](https://cheatsheetseries.owasp.org/cheatsheets/Secrets_Management_Cheat_Sheet.html) 166 | 167 | ## Preventing Brute Force Attacks 168 | 169 | Implement rate limiting and account lockout mechanisms on your backend to prevent brute force attacks. 170 | 171 | ### Example: Rate Limiting with Express-rate-limit 172 | 173 | ```js 174 | const rateLimit = require("express-rate-limit"); 175 | 176 | const apiLimiter = rateLimit({ 177 | windowMs: 15 * 60 * 1000, // 15 minutes 178 | max: 100, 179 | message: "Too many requests from this IP, please try again after 15 minutes", 180 | }); 181 | 182 | app.use("/api/", apiLimiter); 183 | ``` 184 | 185 | ## Preventing Password Theft via Reset Links 🔗🔑 186 | 187 | ### Understanding the Risk 188 | 189 | 190 | 191 | When users click a password reset link (e.g., `https://example.com/reset-password?token=12345`), the page may load external resources, potentially exposing the URL with the token. 192 | 193 | [To learn more ↗️](https://web.dev/articles/referrer-best-practices/) 194 | 195 | ### Mitigating the Risk 196 | 197 | Implement a `Referrer-Policy` on both the backend (for global settings) and the frontend (for specific pages, especially in SPA frameworks like React or Next.js). This policy controls the referrer information sent to other domains, protecting sensitive data in the URL. 198 | 199 | #### Backend Implementation in Express.js 200 | 201 | ```javascript 202 | app.use((req, res, next) => { 203 | res.setHeader("Referrer-Policy", "origin-when-cross-origin"); 204 | next(); 205 | }); 206 | ``` 207 | 208 | #### Frontend Implementation in React.js/Next.js 209 | 210 | Use `react-helmet` (React) or set headers in `_document.js` (Next.js) to include the `Referrer-Policy`. 211 | 212 | ```jsx 213 | // React with react-helmet 214 | 215 | 216 | 217 | 218 | // Next.js in _document.js 219 | 220 | 221 | 222 | ``` 223 | 224 | ## Preventing Parameter Tampering 💸 225 | 226 | ### Understanding the Risk 227 | 228 | In e-commerce applications or any other payment related application, parameter tampering can occur if user-supplied data like product prices or quantities are trusted blindly. Attackers might manipulate these values to reduce prices or change order details. 229 | 230 | ### Bad Practice: Trusting Client-Supplied Prices 231 | 232 | ```javascript 233 | // Vulnerable to parameter tampering 234 | app.post("/process-payment", (req, res) => { 235 | const { productId, userPrice } = req.body; 236 | // Using userPrice for transaction 237 | }); 238 | ``` 239 | 240 | ### Good Practice: Server-Side Price Validation 241 | 242 | ```javascript 243 | // Secure approach 244 | app.post("/process-payment", (req, res) => { 245 | const { productId } = req.body; 246 | const actualPrice = getProductPrice(productId); // Fetch the real price from the server 247 | // Process payment with actualPrice, avoiding tampering 248 | }); 249 | ``` 250 | 251 | In the secure approach, the server retrieves the actual price based on the product ID from a reliable source, like a database, ensuring the integrity of the transaction. 252 | 253 | ## Conclusion 254 | 255 | Writing secure code involves being mindful of user input, safeguarding database queries, and preventing unauthorized actions. Adhering to secure coding practices significantly reduces vulnerability risks. For in-depth techniques, refer to resources like the OWASP Top Ten, and regularly update your security knowledge. 256 | 257 | ## References 258 | 259 | - [OWASP Top Ten](https://owasp.org/www-project-top-ten/) 260 | - [OWASP Secure Coding Practices](https://cheatsheetseries.owasp.org/index.html) 261 | -------------------------------------------------------------------------------- /images/hero-dark.svg: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /docs/programming-case-types.mdx: -------------------------------------------------------------------------------- 1 | --- 2 | title: "Naming Conventions in Software Development" 3 | sidebarTitle: "Naming Conventions" 4 | description: "Explore best practices for naming files, functions, variables, and more in software development, with examples of good and bad practices." 5 | icon: "tag" 6 | og:site_name: "Software Development Essentials" 7 | og:title: "Naming Conventions in Software Development" 8 | og:description: "Understand the importance and methodologies of effective naming conventions in various aspects of software development." 9 | og:url: "https://peacockindia.mintlify.app/docs/programming-case-types" 10 | og:image: "https://images.unsplash.com/photo-1516703914899-e8303d01329a?q=80&w=3270&auto=format&fit=crop&ixlib=rb-4.0.3&ixid=M3wxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8fA%3D%3D" 11 | og:image:width: "1200" 12 | og:image:height: "630" 13 | og:locale: "en_US" 14 | article:publisher: "https://github.com/jacksonkasi1" 15 | twitter:title: "Naming Conventions in Software Development" 16 | twitter:description: "Master the art of naming in software development for improved clarity and consistency." 17 | twitter:url: "https://peacockindia.mintlify.app/docs/programming-case-types" 18 | twitter:image: "https://images.unsplash.com/photo-1516703914899-e8303d01329a?q=80&w=3270&auto=format&fit=crop&ixlib=rb-4.0.3&ixid=M3wxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8fA%3D%3D" 19 | twitter:site: "@jacksonkasi11" 20 | --- 21 | 22 | 23 | Using a Centralized Typography Component in React 28 | 29 | 30 | Adopting effective naming conventions is crucial in software development for ensuring code clarity, maintainability, and ease of collaboration. This guide covers various aspects of naming, from file names to constants, providing guidelines for best practices. 31 | 32 | ## CamelCase 33 | 34 | Used for object keys, function names, React state variables, and more. 35 | 36 | ### Object Naming 37 | 38 | State object keys should be descriptive and follow camelCase. 39 | 40 | **Good Practice**: 41 | ```js 42 | { 43 | firstName: "", 44 | lastName: "", 45 | paymentId: "", 46 | } 47 | ``` 48 | 49 | **Bad Practice**: 50 | ```js 51 | { 52 | first: "", // Not descriptive 53 | lname: "", // Inconsistent naming 54 | id_payment: "", // Mixed naming styles 55 | } 56 | ``` 57 | 58 | ### Hook naming 59 | 60 | Combine 'use', action, and resource for clarity. 61 | 62 | **Good Practice**: 63 | 64 | ```js 65 | function useLocalStorage() { /* ... */ } 66 | function useClickOutside() { /* ... */ } 67 | 68 | function useGetUserProfileAPI() { /* ... swr api function */ } 69 | function useUserLoginAPI() { /* ... swr api function */ } 70 | ``` 71 | 72 | **Bad Practice**: 73 | 74 | ```js 75 | function getUserProfile() { /* ... */ } // Not clear it's a hook 76 | function loginAPI() { /* ... */ } // Should start with 'use' and describe action 77 | ``` 78 | 79 | ### Function Naming 80 | 81 | Function names should clearly indicate their purpose and action. 82 | 83 | **Good Practice**: 84 | 85 | ```js 86 | function handleChange() { /* ... */ } 87 | function handleSubmit() { /* ... */ } 88 | function getUserProfileAPI() { /* ... */ } // REST API Call Function 89 | ``` 90 | 91 | **Bad Practice**: 92 | ```js 93 | function handle() { /* ... */ } // Too vague 94 | function submitData() { /* ... */ } // Verb should come first 95 | ``` 96 | 97 | ## PascalCase 98 | 99 | Used for class names, constructor functions, and React component names. 100 | 101 | ### Type Naming: `UserProfile` 102 | 103 | **Good Example:** 104 | ```typescript 105 | type UserProfile = { 106 | id: number; 107 | name: string; 108 | email: string; 109 | }; 110 | ``` 111 | 112 | **Bad Example:** 113 | ```typescript 114 | type user_info = { 115 | userid: number; 116 | username: string; 117 | useremail: string; 118 | }; 119 | ``` 120 | 121 | ### Interface Naming: `UserSettings` 122 | 123 | **Good Example:** 124 | ```typescript 125 | interface UserSettings { 126 | theme: string; 127 | notifications: boolean; 128 | } 129 | ``` 130 | 131 | **Bad Example:** 132 | ```typescript 133 | interface settings { 134 | Theme: string; 135 | NotificationsEnabled: boolean; 136 | } 137 | ``` 138 | 139 | ## snake_case 140 | 141 | Commonly used for database fields and table names. 142 | 143 | ### Database Schema Naming 144 | 145 | **Tables Naming**: 146 | 147 | Good Practice: 148 | ```plaintext 149 | tbl_users 150 | tbl_payment_history 151 | ``` 152 | 153 | Bad Practice: 154 | ```js 155 | usersTable // Prefix 'tbl_' makes it clear it's a table 156 | paymentHistory // Lacks prefix 157 | ``` 158 | 159 | **Table Fields Naming**: 160 | 161 | Good Practice: 162 | 163 | ```plaintext 164 | first_name 165 | last_name 166 | email_address 167 | ``` 168 | 169 | Bad Practice: 170 | 171 | ```js 172 | FirstName // Use snake_case for database fields 173 | last name // Avoid spaces; use underscores 174 | emailAddress // Stick to one case style, preferably snake_case 175 | ``` 176 | 177 | ## UPPER_CASE_SNAKE_CASE 178 | 179 | Used for constants and environment variable names 180 | 181 | ### Constants 182 | 183 | **Good Practice**: 184 | 185 | ```js 186 | const MAX_RETRY_COUNT = 3; 187 | const DEFAULT_TIMEOUT = 1000; 188 | const API_BASE_URL = 'https://api.example.com'; 189 | ``` 190 | 191 | **Bad Practice**: 192 | 193 | ```js 194 | const maxRetry = 3; // Should be uppercase 195 | const DefaultTimeout = 1000; // Should not use camelCase or PascalCase 196 | const ApiBaseUrl = 'https://...';// Constants should be in uppercase 197 | ``` 198 | 199 | ### Environment Variables 200 | 201 | **Good Practice**: 202 | ```plaintext 203 | DATABASE_URL 204 | ACCESS_TOKEN_SECRET 205 | REDIS_PORT 206 | ``` 207 | 208 | **Bad Practice**: 209 | ```js 210 | dbUrl // Not uppercase 211 | accessToken // Should use underscores to separate words 212 | RedisPort // Not following the uppercase convention 213 | ``` 214 | 215 | ## kebab-case 216 | 217 | Used for CSS class names and URL slugs. 218 | 219 | ### CSS Class Naming 220 | 221 | **Good Practice**: 222 | 223 | ```css 224 | .btn-primary 225 | .btn-secondary 226 | ``` 227 | 228 | **Bad Practice**: 229 | 230 | ```css 231 | .btnPrimary 232 | .btnSecondary 233 | ``` 234 | 235 | ## Other Naming Conventions ✨ 236 | 237 | ### Configuration Files 238 | 239 | Configuration file names should indicate their purpose and the environment they're used in. 240 | 241 | **Good Practice**: 242 | 243 | ```plaintext 244 | development.config.js 245 | production.config.js 246 | test.config.js 247 | ``` 248 | 249 | **Bad Practice**: 250 | ```js 251 | configDev.js // Inconsistent naming 252 | prodConfig.js // Ambiguity in file purpose 253 | test_conf.js // Mixing naming styles 254 | ``` 255 | 256 | 257 | Certainly! Let's include examples for folder naming conventions as well. In software development, folder names are typically given in `PascalCase` or `kebab-case`, depending on the project's convention. Here's how I would incorporate this into the document: 258 | 259 | --- 260 | 261 | ### Folder Naming 262 | 263 | Folder names should be clear, consistent, and indicative of their contents. Depending on the project's convention, `PascalCase` or `kebab-case` can be used. 264 | 265 | 266 | Recommend using `kebab-case` for folder names. 267 | 268 | 269 | **PascalCase for Folder Naming** 270 | 271 | Good Practice: 272 | 273 | ```plaintext 274 | Components/ 275 | Utilities/ 276 | AuthPages/ 277 | UserProfile/ 278 | ``` 279 | 280 | Bad Practice: 281 | 282 | ```js 283 | components/ // Should be PascalCase for consistency 284 | utilities_folder/ // Should not mix cases or use underscores 285 | auth-pages/ // Should use either kebab-case or PascalCase consistently 286 | UserProfilePage/ // Redundant 'Page' suffix in a folder name 287 | ``` 288 | 289 | **kebab-case for Folder Naming** 290 | 291 | Good Practice: 292 | 293 | ```plaintext 294 | components/ 295 | utilities/ 296 | auth-pages/ 297 | user-profile/ 298 | ``` 299 | 300 | Bad Practice: 301 | 302 | ```js 303 | Components/ // Should be lowercase for kebab-case 304 | utilitiesFolder/ // Should use dashes, not camelCase 305 | Auth_Pages/ // Avoid mixing case styles and underscores 306 | UserProfilePage/ // Redundant 'Page' suffix and incorrect case style 307 | ``` 308 | 309 | ### File Naming Conventions 310 | 311 | File naming conventions organize and simplify your code, making it easier for teams to navigate. This guide emphasizes best practices for naming React components and files such as hooks and utils. It also warns against common mistakes to keep your project clear and consistent. 312 | 313 | **Component Files (JSX/TSX)** 314 | 315 | | Good Practice ✅ 316 | 317 | React component files should be named using **PascalCase**. 318 | 319 | ```plaintext 320 | UserProfile.jsx 321 | InvoiceList.tsx 322 | ``` 323 | 324 | | Bad Practice ❌ 325 | 326 | Avoid using `snake_case`, `kebab-case`, or inconsistent capitalization in component filenames. 327 | 328 | ```plaintext 329 | user_profile.jsx // snake_case 330 | invoice-list.tsx // kebab-case 331 | userprofile.js // all lowercase 332 | ``` 333 | 334 | **Hooks/Utils/Other JS or TS Files** 335 | 336 | For non-component files, you have the option between `kebab-case` and `camelCase`. The key is to maintain consistency throughout the project. Choose one style and stick with it. 337 | 338 | | Good Practice ✅ 339 | 340 | - Using Kebab-Case 341 | ```plaintext 342 | use-user-data.js 343 | format-date.ts 344 | user-types.ts 345 | ``` 346 | 347 | - Using CamelCase 348 | ```plaintext 349 | useUserData.js 350 | formatDate.ts 351 | userTypes.ts 352 | ``` 353 | 354 | | Bad Practice ❌ 355 | 356 | Mixing naming conventions within the same project or using unconventional casing can lead to a cluttered and confusing codebase. 357 | 358 | ```plaintext 359 | useUserData.js // CamelCase mixed with... 360 | format-date.ts // kebab-case in the same project 361 | 362 | UseUserData.js // PascalCase for non-component files 363 | formatDate.TS // Inconsistent file extension casing 364 | ``` 365 | 366 | #### Recommendation 📌 367 | 368 | Decide whether to use `kebab-case` or `camelCase` for naming hooks, utilities, types, and other similar files in your project. **Do not mix** these conventions within the same codebase. 369 | 370 | The choice may depend on team preferences, the specific needs of the project, or existing conventions in related projects. Remember, consistency is paramount. 371 | 372 | --- 373 | 374 | 375 | ## Programming Case Styles Cheat Sheet📘 376 | 377 | Quick Reference for Naming Conventions in Different Programming Scenarios 378 | 379 | | Case Style | Usage | 380 | |-------------------------|-------------------------------------------------------------| 381 | | camelCase | Object keys, function names, variables, React state variables, method names in classes | 382 | | PascalCase | Class names, constructor functions, React component names, interface names (in languages like TypeScript) | 383 | | snake_case | Database fields, database table names, variable and function names in Python | 384 | | kebab-case | CSS class names, file names, URL slugs | 385 | | UPPER_CASE_SNAKE_CASE | Constants, environment variable names | 386 | | Hungarian Notation | Prefixing variable names with type indicators (less common) | 387 | 388 | 389 | 390 | ## Conclusion 391 | 392 | Adopting clear and consistent naming conventions enhances the overall quality of your codebase, making it more accessible and easier to maintain. By following these guidelines, you'll foster a more efficient and collaborative development environment. 393 | 394 | 395 | -------------------------------------------------------------------------------- /docs/typography.mdx: -------------------------------------------------------------------------------- 1 | --- 2 | title: "Using a Centralized Typography Component in React" 3 | sidebarTitle: "Centralized Typography" 4 | description: "Learn how to maintain consistent typography across your React application using a centralized Typography component." 5 | icon: "t" 6 | og:site_name: "React Typography Best Practices" 7 | og:title: "Using a Centralized Typography Component in React" 8 | og:description: "A guide to implementing a centralized Typography component in React for uniform and manageable text styles." 9 | og:url: "https://peacockindia.mintlify.app/docs/typography" 10 | og:image: "https://images.unsplash.com/photo-1703769605307-395ace742240?q=80&w=3280&auto=format&fit=crop&ixlib=rb-4.0.3" 11 | og:image:width: "1200" 12 | og:image:height: "630" 13 | og:locale: "en_US" 14 | article:publisher: "https://github.com/jacksonkasi1" 15 | twitter:title: "Centralized Typography in React" 16 | twitter:description: "Streamline your React application's typography with a centralized component approach." 17 | twitter:url: "https://peacockindia.mintlify.app/docs/typography" 18 | twitter:image: "https://images.unsplash.com/photo-1703769605307-395ace742240?q=80&w=3280&auto=format&fit=crop&ixlib=rb-4.0.3" 19 | twitter:site: "@jacksonkasi11" 20 | --- 21 | 22 | 23 | Using a Centralized Typography Component in React 28 | 29 | 30 | In React development, maintaining consistent typography across different parts of the application can be challenging. Often, developers find themselves repeating styles for text elements, leading to a cluttered and difficult-to-manage codebase 😔. This document outlines the problem and introduces a solution: using a centralized Typography component. 31 | 32 | ## The Problem with Repetitive Inline Styling 33 | 34 | Repetitive inline styling for text elements is a common issue. It not only clutters your code but also makes it difficult to maintain and update styles consistently across your application. 35 | 36 | ### Bad Practice Example 📛 37 | 38 | Here's an example of what to avoid: 39 | 40 | ```js 41 |

Login Page

42 |

43 | hello world 44 |

45 | ``` 46 | 47 | ## The Solution: Centralized Typography Component 48 | 49 | A better approach is to use a centralized Typography component. This approach ensures consistency, adheres to the DRY (Don't Repeat Yourself) principle, and simplifies updates to your site's typography. 50 | 51 | ### Good Practice Example ✅ 52 | 53 | Here's how you can use the Typography component: 54 | 55 | ```js 56 | Login Page 57 | 58 | 61 | ``` 62 | 63 | ## Benefits of Using a Centralized Typography Component 64 | 65 | - **Consistency**: Ensures that typography is consistent throughout the application. 66 | - **Maintainability**: Makes it easier to update and maintain styles. 67 | - **Adherence to DRY Principle**: Avoids repetition of similar code, saving development time. 68 | - **Flexibility**: Allows for easy changes to the site's overall typography from a single location. 69 | - **Responsiveness**: Ensures that typography is responsive across different screen sizes. 70 | 71 | ## Typography Component Overview 72 | 73 | The Typography component is designed to handle various text styles and animations. Here's a brief overview of its structure and usage: 74 | 75 | ```js 76 | // Import statements 77 | import React from "react"; 78 | import { Link, useNavigate } from "react-router-dom"; 79 | import { motion as m } from "framer-motion"; 80 | 81 | // Component definition... 82 | ``` 83 | 84 | ### Component Props 85 | 86 | - **variant**: Specifies the text style variant. 87 | - **children**: The content to be rendered. 88 | - **className**: Additional CSS classes. 89 | - **maxLines**: Maximum number of lines to display. 90 | - **navigate**: Direction of navigation for links. 91 | - **link**: URL for navigation. 92 | - **target**: Target attribute for the link. 93 | - **animate**: Type of animation. 94 | - **disableSelect**: If true, disables text selection. 95 | 96 | ### Usage Example 97 | 98 | ```js 99 | 100 | Welcome to Our Site 101 | 102 | ``` 103 | 104 | ## Example `Typography.jsx` 105 | 106 | Click on the following dropdown to view a sample `Typography.jsx` file with all the available variants and animations. But this typography component is not limited to the above variants and animations. You can add as many as you want. You can also add your own custom variants and animations. 107 | 108 | 109 | 110 | ```js Typography.jsx 111 | import React from "react"; 112 | import { Link, useNavigate } from "react-router-dom"; 113 | 114 | // ** third party library 115 | import { motion as m } from "framer-motion"; 116 | 117 | /** 118 | * @typedef {'T_Bold_H1' | 'T_Bold_H2' | 'T_Bold_H3' | 'T_Bold_H4' | 'T_Bold_H5' | 'T_Bold_H6' | 119 | * 'T_SemiBold_H1' | 'T_SemiBold_H2' | 'T_SemiBold_H3' | 'T_SemiBold_H4' | 'T_SemiBold_H5' | 'T_SemiBold_H6' | 120 | * 'T_Medium_H1' | 'T_Medium_H2' | 'T_Medium_H3' | 'T_Medium_H4' | 'T_Medium_H5' | 'T_Medium_H6' | 121 | * 'T_Regular_H1' | 'T_Regular_H2' | 'T_Regular_H3' | 'T_Regular_H4' | 'T_Regular_H5' | 'T_Regular_H6'} TypographyVariant 122 | * @typedef {'move' | 'underline'} TypographyAnimation 123 | * @typedef {'forward' | 'back'} LinkDirection 124 | */ 125 | 126 | /** 127 | * Represents a Typography component with various text styles and animations. 128 | * 129 | * @component 130 | * @param {object} props - The component props. 131 | * @param {TypographyVariant} props.variant - The text variant. 132 | * @param {React.ReactNode} props.children - The content to display. 133 | * @param {string} props.className - Additional CSS classes for styling. 134 | * @param {number} props.maxLines - Maximum number of lines to display (0 for no limit). 135 | * @param {LinkDirection} [props.navigate] - The direction of the link. 136 | * @param {string} props.link - Optional link URL. 137 | * @param {string} props.target - Target attribute for the link. 138 | * @param {TypographyAnimation} props.animate - Animation type ('move' or 'underline'). 139 | * @param {boolean} props.disableSelect - Disable selection 140 | * @param {React.ReactNode} props.children - The content to display. 141 | * @returns {React.ReactNode} The rendered Typography component. 142 | * 143 | * @example 144 | * // Example usage of Typography component 145 | * Hello, World! 146 | */ 147 | 148 | function Typography({ 149 | mVariants, 150 | mDelay = 0, 151 | variant, 152 | children, 153 | className, 154 | maxLines, 155 | navigate, 156 | link = "", 157 | target = "", 158 | animate = "", 159 | disableSelect = false, // Added the new prop with a default value of false 160 | ...props 161 | }) { 162 | if (!variant) { 163 | throw new Error("variant is required"); 164 | } 165 | 166 | const getClassName = () => { 167 | switch (variant) { 168 | // "Bold" - 700 169 | case "T_Bold_H1": 170 | return "font-poppins font-bold text-[40px] md:text-[62px] tracking-normal"; 171 | case "T_Bold_H2": 172 | return "font-poppins font-bold text-[32px] md:text-[49px] tracking-normal"; 173 | case "T_Bold_H3": 174 | return "font-poppins font-bold text-[24px] md:text-[39px] tracking-normal"; 175 | case "T_Bold_H4": 176 | return "font-poppins font-bold text-[20px] md:text-[25px] tracking-normal"; 177 | case "T_Bold_H5": 178 | return "font-poppins font-bold text-[16px] md:text-[20px] tracking-normal"; 179 | case "T_Bold_H6": 180 | return "font-poppins font-bold text-[14px] md:text-[16px] tracking-normal"; 181 | 182 | // "SemiBold" - 600 183 | case "T_SemiBold_H1": 184 | return "font-poppins font-semibold text-[40px] md:text-[62px] tracking-normal"; 185 | case "T_SemiBold_H2": 186 | return "font-poppins font-semibold text-[32px] md:text-[49px] tracking-normal"; 187 | case "T_SemiBold_H3": 188 | return "font-poppins font-semibold text-[24px] md:text-[39px] tracking-normal"; 189 | case "T_SemiBold_H_T": 190 | return "font-poppins font-semibold text-[24px] md:text-[31px] tracking-normal"; 191 | case "T_SemiBold_H4": 192 | return "font-poppins font-semibold text-[20px] md:text-[25px] tracking-normal"; 193 | case "T_SemiBold_H5": 194 | return "font-poppins font-semibold text-[16px] md:text-[20px] tracking-normal"; 195 | case "T_SemiBold_H6": 196 | return "font-poppins font-semibold text-[14px] md:text-[16px] tracking-normal"; 197 | 198 | // "Medium" - 500 199 | case "T_Medium_H1": 200 | return "font-poppins font-medium text-[40px] md:text-[62px] tracking-normal"; 201 | case "T_Medium_H2": 202 | return "font-poppins font-medium text-[32px] md:text-[49px] tracking-normal"; 203 | case "T_Medium_H3": 204 | return "font-poppins font-medium text-[24px] md:text-[39px] tracking-normal"; 205 | case "T_Medium_H4": 206 | return "font-poppins font-medium text-[20px] md:text-[25px] tracking-normal"; 207 | case "T_Medium_H5": 208 | return "font-poppins font-medium text-[16px] md:text-[20px] tracking-normal"; 209 | case "T_Medium_H6": 210 | return "font-poppins font-medium text-[14px] md:text-[16px] tracking-normal"; 211 | case "T_Medium_H7": 212 | return "font-poppins font-medium text-[10px] md:text-[14px] tracking-normal"; 213 | 214 | // "Regular" - 400 215 | case "T_Regular_H1": 216 | return "font-poppins font-normal text-[40px] md:text-[62px] tracking-normal"; 217 | case "T_Regular_H2": 218 | return "font-poppins font-normal text-[32px] md:text-[49px] tracking-normal"; 219 | case "T_Regular_H3": 220 | return "font-poppins font-normal text-[24px] md:text-[39px] tracking-normal"; 221 | case "T_Regular_H4": 222 | return "font-poppins font-normal text-[20px] md:text-[25px] tracking-normal"; 223 | case "T_Regular_H5": 224 | return "font-poppins font-normal text-[16px] md:text-[20px] tracking-normal"; 225 | case "T_Regular_H6": 226 | return "font-poppins font-normal text-[14px] md:text-[16px] tracking-normal"; 227 | 228 | default: 229 | return ""; 230 | } 231 | }; 232 | 233 | const fontTypes = getClassName(); 234 | 235 | const lineClampClass = 236 | maxLines > 0 ? `line-clamp-${maxLines?.toString()}` : "whitespace-normal"; 237 | 238 | const getAnimationClass = () => { 239 | switch (animate) { 240 | case "move": 241 | return "hover:ml-1.5 transition-all duration-300"; 242 | case "underline": 243 | return "hover:underline transition-all duration-300"; 244 | default: 245 | return ""; 246 | } 247 | }; 248 | 249 | const animationClass = getAnimationClass(); 250 | 251 | const navigator = useNavigate(); 252 | 253 | const handleNavigate = () => { 254 | if (navigate === "back") { 255 | navigator(-1); 256 | } else { 257 | navigator(1); 258 | } 259 | }; 260 | 261 | const content = ( 262 | { 272 | if (props?.onClick) { 273 | props?.onClick(); // Execute the props.onClick function if it exists 274 | } 275 | if (navigate) { 276 | handleNavigate(); // Execute handleNavigate if it exists 277 | } 278 | }} 279 | > 280 | {children} 281 | 282 | ); 283 | 284 | return link ? ( 285 | 286 | {content} 287 | 288 | ) : ( 289 | content 290 | ); 291 | } 292 | 293 | Typography.defaultProps = { 294 | className: "", 295 | maxLines: 0, 296 | animate: "", 297 | }; 298 | 299 | export default Typography; 300 | ``` 301 | 302 | 303 | 304 | By integrating this Typography component into your React project, you can significantly enhance the readability and maintainability of your code, ensuring a consistent and professional appearance across your application. 305 | -------------------------------------------------------------------------------- /docs/code-splitting.mdx: -------------------------------------------------------------------------------- 1 | --- 2 | title: "Best Practices for Code Splitting in Web Development" 3 | sidebarTitle: "Code Splitting" 4 | description: "Learn the importance of modular code organization, with examples of good and bad practices in React.js projects." 5 | icon: "knife" 6 | og:site_name: "Web Development Essentials" 7 | og:title: "Best Practices for Code Splitting in Web Development" 8 | og:description: "Master the techniques of effective code splitting in React.js for more efficient web applications." 9 | og:url: "https://peacockindia.mintlify.app/docs/code-splitting" 10 | og:image: "https://images.unsplash.com/photo-1464002255390-2de63a26c637?q=80&w=3270&auto=format&fit=crop&ixlib=rb-4.0.3&ixid=M3wxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8fA%3D%3D" 11 | og:image:width: "1200" 12 | og:image:height: "630" 13 | og:locale: "en_US" 14 | article:publisher: "https://github.com/jacksonkasi1" 15 | twitter:title: "Best Practices for Code Splitting in Web Development" 16 | twitter:description: "Explore good and bad practices in modular code organization in React.js." 17 | twitter:url: "https://peacockindia.mintlify.app/docs/code-splitting" 18 | twitter:image: "https://images.unsplash.com/photo-1464002255390-2de63a26c637?q=80&w=3270&auto=format&fit=crop&ixlib=rb-4.0.3&ixid=M3wxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8fA%3D%3D" 19 | twitter:site: "@jacksonkasi11" 20 | --- 21 | 22 | 23 | Best Practices for Import Statements in React 28 | 29 | 30 | Effective code organization is key to maintaining a scalable, readable, and maintainable codebase. This document discusses good and bad practices in code splitting, particularly in the context of React.js development, and provides examples for a more modular code structure. 31 | 32 | ## The Problem with Monolithic Code Structures ⚠️ 33 | 34 | Monolithic or single-file code structures can lead to several issues: 35 | 36 | - **Difficult Maintenance**: Large files with mixed concerns are harder to understand and maintain. 37 | - **Poor Readability**: Finding specific code segments becomes challenging as the file size grows. An example from personal experience is encountering files extending to 15,000 lines of code, which can be overwhelming and difficult to manage. 38 | - **Name Clashing**: In extensive single files, reusing names for functions or components across different contexts can lead to conflicts and confusion, making debugging difficult. 39 | 40 | ### Bad Practice Example 📛 41 | 42 | Avoid placing all components, utilities, and types in one large file. For instance, defining multiple modals, utilities, and type declarations in a single file leads to clutter and confusion. 43 | 44 | 45 | ```js Example Large files 46 | // Bad Practice: Everything in one file 47 | import React from 'react'; 48 | // Imports for components, utilities, types all mixed together... 49 | 50 | const MyComponent = () => { /* ... */ }; 51 | const AnotherComponent = () => { /* ... */ }; 52 | // Multiple components and utility functions defined here... 53 | 54 | // thousands of lines of code... 🚂 55 | 56 | export default MyComponent; 57 | ``` 58 | 59 | ```js Name Clashing Example 1 60 | // Function to calculate the area of a circle 61 | function calculateArea(radius) { 62 | return Math.PI * radius * radius; 63 | } 64 | 65 | // Later in the same file, another calculateArea function is defined for a square 66 | function calculateArea(side) { 67 | return side * side; 68 | } 69 | 70 | // Usage 71 | const circleArea = calculateArea(5); // Intended to calculate area of a circle 72 | ``` 73 | 74 | ```js Name Clashing Example 2 75 | 76 | import React, { useState } from 'react'; 77 | 78 | const LargeComponent = () => { 79 | // First useState for user input 80 | const [input, setInput] = useState(''); 81 | 82 | const handleInputChange = (e) => { 83 | setInput(e.target.value); 84 | }; 85 | 86 | // ... many other states and handlers ... 87 | 88 | // Accidental redeclaration of the same state and handler 89 | const [input, setInput] = useState(''); 90 | 91 | const handleInputChange = () => { 92 | // Logic intended for a different purpose 93 | }; 94 | 95 | // ... more code ... 96 | 97 | return ( 98 |
99 | 100 | {/* Other components and logic */} 101 |
102 | ); 103 | }; 104 | ``` 105 |
106 | 107 | ## Good Practices in Code Splitting 🚀 108 | 109 | ### Modular Component Structure 110 | 111 | Organize components into separate files and directories. This improves readability and maintenance. 112 | 113 | ```js 114 | // Good Practice: Modular structure with sub-components 115 | import React from 'react'; 116 | import SuccessModal from './SuccessModal'; 117 | // ...other imports 118 | 119 | const Modal = ({ variant, ...props }) => { 120 | // Component logic 121 | return
{/* Render selected modal based on variant */}
; 122 | }; 123 | 124 | export default Modal; 125 | ``` 126 | 127 | Example: Modal Component Structure 128 | 129 | ```mdx 130 | . 131 | └── Modal/ 132 | ├── index.jsx 133 | ├── SuccessModal.jsx 134 | ├── WarningModal.jsx 135 | ├── DangerModal.jsx 136 | ├── LoginModal.jsx 137 | ``` 138 | 139 | ### Modal Component Code example 🤓 140 | 141 | 142 | 143 | 144 | 145 | ```js index.jsx 146 | import React from 'react'; 147 | 148 | // ** import sub components 149 | import SuccessModal from './SuccessModal'; 150 | import WarningModal from './WarningModal'; 151 | import DangerModal from './DangerModal'; 152 | import LoginModal from './LoginModal'; 153 | 154 | /** 155 | * @typedef {'success' | 'warning' | 'danger' | 'login'} ModalVariant 156 | * @typedef {'opaque' | 'blur' | 'transparent'} BackdropVariant 157 | * @typedef {'auto' | 'top' | 'center' | 'bottom' | 'bottom-center' | 'top-center'} placement 158 | */ 159 | 160 | /** 161 | * Modal component. 162 | * 163 | * @param {Object} props - The component props. 164 | * @param {ModalVariant} props.variant - The variant of the header to render. 165 | * @param {string} props.title 166 | * @param {string} props.description 167 | * @param {string} props.yesText 168 | * @param {string}props.noText 169 | * @param {Function} props.btnFunction - The function to call when button is clicked. 170 | * @param {Function} props.yesFunction - The function to call when 'yes' is clicked. 171 | * @param {Function} props.noFunction - The function to call when 'no' is clicked. 172 | * @param {BackdropVariant} props.backdropVariant - The variant of the backdrop to render. 173 | * @param {boolean} props.hideCloseButton - A boolean indicating whether a close button is present. 174 | * @param {boolean} props.outsideClickClose - The boolean indicating whether the modal should close when clicking outside the modal 175 | * @param {placement} props.placement - The placement of the modal 176 | * @returns {JSX.Element|null} The rendered header component. 177 | * 178 | */ 179 | const Modal = ({ variant, ...props }) => { 180 | const variantComponents = { 181 | success: SuccessModal, 182 | warning: WarningModal, 183 | danger: DangerModal, 184 | login: LoginModal 185 | }; 186 | 187 | const SelectedModal = variantComponents[variant] || null; 188 | 189 | return
{SelectedModal && }
; 190 | }; 191 | 192 | export default Modal; 193 | ``` 194 | 195 | ```js SuccessModal.jsx 196 | import React from 'react'; 197 | 198 | // ** import next ui 199 | import { Modal, ModalContent } from '@nextui-org/react'; 200 | 201 | // ** import shared components 202 | import Typography from '@shared/Typography'; 203 | import Button from '@shared/Button'; 204 | 205 | // ** import assets 206 | import SuccessSvg from '@icons/SuccessSvg'; 207 | 208 | // ** import redux 209 | import { useSelector, useDispatch } from 'react-redux'; 210 | import { setAlertModel } from '@redux/slices/utils'; 211 | 212 | /** 213 | * @typedef {'opaque' | 'blur' | 'transparent'} BackdropVariant 214 | * @typedef {'auto' | 'top' | 'center' | 'bottom' | 'bottom-center' | 'top-center'} placement 215 | */ 216 | 217 | /** 218 | * SuccessModal component. 219 | * 220 | * @param {Object} props - The component props. 221 | * @param {string} props.title - The title for the modal. 222 | * @param {string} props.description - The description for the modal. 223 | * @param {string} props.btnText - The text for the button. 224 | * @param {Function} props.btnFunction - The function to call when the button is clicked. 225 | * @param {BackdropVariant} props.backdropVariant - The variant of the backdrop to render. 226 | * @param {boolean} props.hideCloseButton - A boolean indicating whether a close button is present. 227 | * @param {placement} props.placement - The placement of the modal 228 | * @param {boolean} props.outsideClickClose - A boolean indicating whether the outside click closes the modal 229 | * @returns {JSX.Element} The rendered SuccessModal component. 230 | */ 231 | const SuccessModal = ({ 232 | title, 233 | description, 234 | btnText, 235 | btnFunction, 236 | backdropVariant = 'blur', // default backdrop is blur 237 | hideCloseButton = true, // default hide close button 238 | placement = 'center', // default placement is center 239 | outsideClickClose = true, // default outside click true 240 | }) => { 241 | const dispatch = useDispatch(); 242 | const { alertModel } = useSelector((state) => state.utils); 243 | 244 | /** 245 | * Handles the close action. 246 | */ 247 | const handleClose = () => { 248 | dispatch(setAlertModel(false)); 249 | if (btnFunction) { 250 | btnFunction(); 251 | } 252 | }; 253 | 254 | /** 255 | * Handles the outside click action. 256 | */ 257 | const handleOutsideClick = () => { 258 | if (outsideClickClose) { 259 | dispatch(setAlertModel(false)); 260 | } 261 | }; 262 | 263 | return ( 264 | 271 | 272 | 273 |
274 | 275 |
276 | 277 | 278 | {title} 279 | 280 | 281 | 285 | {description} 286 | 287 |
288 | 291 |
292 |
293 |
294 | ); 295 | }; 296 | 297 | export default SuccessModal; 298 | ``` 299 | 300 | ```js WarningModal.jsx 301 | import React from 'react'; 302 | 303 | // ** import next ui 304 | import { Modal, ModalContent } from '@nextui-org/react'; 305 | 306 | // ** import shared components 307 | import Typography from '@shared/Typography'; 308 | import Button from '@shared/Button'; 309 | 310 | // ** import assets 311 | import WarningSvg from '@icons/WarningSvg'; 312 | 313 | // ** import redux 314 | import { useSelector, useDispatch } from 'react-redux'; 315 | import { setAlertModel } from '@redux/slices/utils'; 316 | 317 | /** 318 | * @typedef {'opaque' | 'blur' | 'transparent'} BackdropVariant 319 | * @typedef {'auto' | 'top' | 'center' | 'bottom' | 'bottom-center' | 'top-center'} placement 320 | */ 321 | 322 | /** 323 | * WarningModal component. 324 | * 325 | * @param {Object} props - The component props. 326 | * @param {string} props.title - The title for the warning modal. 327 | * @param {string} props.description - The description for the warning modal. 328 | * @param {string} props.yesText - The text for the 'Yes' button. 329 | * @param {string} props.noText - The text for the 'No' button. 330 | * @param {Function} props.yesFunction - The function to call when 'Yes' is clicked. 331 | * @param {Function} props.noFunction - The function to call when 'No' is clicked. 332 | * @param {BackdropVariant} props.backdropVariant - The variant of the backdrop to render. 333 | * @param {boolean} props.hideCloseButton - A boolean indicating whether a close button is present. 334 | * @param {placement} props.placement - The placement of the modal 335 | * @param {boolean} props.outsideClickClose - A boolean indicating whether the outside click closes the modal 336 | * @returns {JSX.Element} The rendered WarningModal component. 337 | */ 338 | const WarningModal = ({ 339 | title, 340 | description, 341 | yesText, 342 | noText, 343 | yesFunction, 344 | noFunction, 345 | backdropVariant = 'blur', // default backdrop is blur 346 | hideCloseButton = true, // default hide close button 347 | placement = 'center', // default placement is center 348 | outsideClickClose = true, // default outside click true 349 | }) => { 350 | const dispatch = useDispatch(); 351 | const { alertModel } = useSelector((state) => state.utils); 352 | 353 | /** 354 | * Function to handle the 'No' button click. 355 | */ 356 | const cancelFunction = () => { 357 | dispatch(setAlertModel(false)); 358 | if (noFunction) { 359 | noFunction(); 360 | } 361 | }; 362 | 363 | /** 364 | * Function to handle the 'Yes' button click. 365 | */ 366 | const confirmFunction = () => { 367 | dispatch(setAlertModel(false)); 368 | if (yesFunction) { 369 | yesFunction(); 370 | } 371 | }; 372 | 373 | /** 374 | * Handles the outside click action. 375 | */ 376 | const handleOutsideClick = () => { 377 | if (outsideClickClose) { 378 | cancelFunction(); 379 | } 380 | }; 381 | 382 | return ( 383 | dispatch(setAlertModel(false))} 391 | > 392 | 393 |
394 | 395 |
396 | 397 | {title} 398 | 399 | 403 | {description} 404 | 405 |
406 | 409 | 412 |
413 |
414 |
415 | ); 416 | }; 417 | 418 | export default WarningModal; 419 | ``` 420 | 421 | ```js DangerModal.jsx 422 | import React from 'react'; 423 | 424 | // ** import next ui 425 | import { Modal, ModalContent } from '@nextui-org/react'; 426 | 427 | // ** import shared components 428 | import Typography from '@shared/Typography'; 429 | import Button from '@shared/Button'; 430 | 431 | // ** import assets 432 | import Danger from '@icons/Danger'; 433 | 434 | // ** import redux 435 | import { useSelector, useDispatch } from 'react-redux'; 436 | import { setAlertModel } from '@redux/slices/utils'; 437 | 438 | /** 439 | * @typedef {'opaque' | 'blur' | 'transparent'} BackdropVariant 440 | * @typedef {'auto' | 'top' | 'center' | 'bottom' | 'bottom-center' | 'top-center'} placement 441 | */ 442 | 443 | /** 444 | * DangerModal component. 445 | * 446 | * @param {Object} props - The component props. 447 | * @param {string} props.title - The title of the modal. 448 | * @param {string} props.description - The description of the modal. 449 | * @param {string} props.yesText - The text for the 'Yes' button. 450 | * @param {string} props.noText - The text for the 'No' button. 451 | * @param {Function} props.yesFunction - The function to call when 'Yes' is clicked. 452 | * @param {Function} props.noFunction - The function to call when 'No' is clicked. 453 | * @param {BackdropVariant} props.backdropVariant - The variant of the backdrop to render. 454 | * @param {boolean} props.hideCloseButton - A boolean indicating whether a close button is present. 455 | * @param {placement} props.placement - The placement of the modal 456 | * @param {boolean} props.outsideClickClose - A boolean indicating whether the outside click closes the modal 457 | * @returns {JSX.Element} The rendered DangerModal component. 458 | */ 459 | const DangerModal = ({ 460 | title, 461 | description, 462 | yesText, 463 | noText, 464 | yesFunction, 465 | noFunction, 466 | backdropVariant = 'blur', // default backdrop is blur 467 | hideCloseButton = true, // default hide close button 468 | placement = 'center', // default placement is center 469 | outsideClickClose = true, // default outside click true 470 | }) => { 471 | const dispatch = useDispatch(); 472 | const { alertModel } = useSelector((state) => state.utils); 473 | 474 | /** 475 | * Function to handle the 'No' button click. 476 | */ 477 | const cancelFunction = () => { 478 | if (noFunction) { 479 | noFunction(); 480 | } 481 | dispatch(setAlertModel(false)); 482 | }; 483 | 484 | /** 485 | * Function to handle the 'Yes' button click. 486 | */ 487 | const confirmFunction = () => { 488 | dispatch(setAlertModel(false)); 489 | if (yesFunction) { 490 | yesFunction(); 491 | } 492 | }; 493 | 494 | /** 495 | * Handles the outside click action. 496 | */ 497 | const handleOutsideClick = () => { 498 | if (outsideClickClose) { 499 | cancelFunction(); 500 | } 501 | }; 502 | 503 | return ( 504 | 511 | 512 |
513 | 514 |
515 | 516 | 517 | {title} 518 | 519 | 520 | 524 | {description} 525 | 526 |
527 | 530 | 533 |
534 |
535 |
536 | ); 537 | }; 538 | 539 | export default DangerModal; 540 | ``` 541 | 542 | ```js LoginModal.jsx 543 | import React from 'react'; 544 | 545 | // ** import next ui 546 | import { Modal, ModalContent } from '@nextui-org/react'; 547 | 548 | // ** import shared components 549 | import Typography from '@shared/Typography'; 550 | import Button from '@shared/Button'; 551 | import Image from '@shared/Image'; 552 | 553 | // ** import assets 554 | import WarningSvg from '@icons/WarningSvg'; 555 | import googleSvg from '@svg/google.svg'; 556 | 557 | // ** import redux 558 | import { useSelector, useDispatch } from 'react-redux'; 559 | import { setLoginModel } from '@redux/slices/utils'; 560 | 561 | // ** import config 562 | import env from '@src/config'; 563 | 564 | /** 565 | * @typedef {'opaque' | 'blur' | 'transparent'} BackdropVariant 566 | * @typedef {'auto' | 'top' | 'center' | 'bottom' | 'bottom-center' | 'top-center'} placement 567 | */ 568 | 569 | /** 570 | * LoginModal component. 571 | * 572 | * @param {Object} props - The component props. 573 | * @param {string} props.title - The title for the modal. 574 | * @param {string} props.description - The description for the modal. 575 | * @param {string} props.btnText - The text for the button. 576 | * @param {Function} props.btnFunction - The function to call when the button is clicked. 577 | * @param {BackdropVariant} props.backdropVariant - The variant of the backdrop to render. 578 | * @param {boolean} props.hideCloseButton - A boolean indicating whether a close button is present. 579 | * @param {placement} props.placement - The placement of the modal 580 | * @param {boolean} props.outsideClickClose - A boolean indicating whether the outside click closes the modal 581 | * @returns {JSX.Element} The rendered LoginModal component. 582 | */ 583 | const LoginModal = ({ 584 | title, 585 | description, 586 | btnText, 587 | btnFunction, 588 | backdropVariant = 'blur', // default backdrop is blur 589 | hideCloseButton = true, // default hide close button 590 | placement = 'center', // default placement is center 591 | outsideClickClose = true, // default outside click true 592 | }) => { 593 | const dispatch = useDispatch(); 594 | const { loginModel } = useSelector((state) => state.utils); 595 | 596 | /** 597 | * Handles the close action. 598 | */ 599 | const handleClose = () => { 600 | dispatch(setLoginModel(false)); 601 | if (btnFunction) { 602 | btnFunction(); 603 | } 604 | }; 605 | 606 | /** 607 | * redirects to google login 608 | */ 609 | const redirectToExternalLink = () => { 610 | try { 611 | dispatch(setLoginModel(false)); 612 | window.location.href = `${env.BASE_URL}/api/v1/auth/google`; 613 | } catch (error) { 614 | console.log("Error at google login", error); 615 | } 616 | }; 617 | 618 | /** 619 | * Handles the outside click action. 620 | */ 621 | const handleOutsideClick = () => { 622 | if (outsideClickClose) { 623 | handleClose(); 624 | } 625 | }; 626 | 627 | return ( 628 | 637 | 638 | 639 |
640 | 641 |
642 | 643 | 644 | {title ?? 'Login required'} 645 | 646 | 647 | 651 | {description ?? 'Please login to enjoy special features'} 652 | 653 |
654 |
655 | 665 |
666 |
667 |
668 |
669 | ); 670 | }; 671 | 672 | export default LoginModal; 673 | ``` 674 |
675 | 676 |
677 | 678 | ### Separate Utilities and Helpers 679 | 680 | Place utility functions and helpers in separate files or directories. 681 | 682 | Example: Utility Function 683 | 684 | ```js 685 | // utils/formatDate.js 686 | export const formatDate = (date) => { 687 | // Format date logic 688 | }; 689 | ``` 690 | 691 | ### Define Types and Interfaces Separately 692 | 693 | For TypeScript or PropTypes in React, define types or interfaces in dedicated files. 694 | 695 | Example: Type Definitions 696 | 697 | ```js 698 | // types/modalTypes.ts 699 | export type ModalVariant = 'success' | 'warning' | 'danger' | 'login'; 700 | ``` 701 | 702 | ### Form Validation in Separate Files 703 | 704 | Keep form validations separate, especially when using libraries like Formik or React Hook Form. 705 | 706 | Example: Form Validation Logic 707 | 708 | ```js 709 | // validation/loginValidation.js 710 | import * as Yup from 'yup'; 711 | 712 | export const loginValidationSchema = Yup.object().shape({ 713 | // Validation schema 714 | }); 715 | ``` 716 | 717 | ## Additional Examples 718 | 719 | - **Component Styles**: Define styles in separate CSS or SCSS files, or use CSS-in-JS styled components. 720 | - **API Calls**: Separate API call functions into a dedicated service or API layer. 721 | - **Contexts and Hooks**: Define React contexts and custom hooks in their own files. 722 | Conclusion 723 | Adopting a modular code structure by splitting your code into logical and coherent units not only enhances readability and maintainability but also prevents conflicts and encourages code reuse. This approach is essential in collaborative environments and large-scale applications. 724 | --------------------------------------------------------------------------------