Organizing the Frontend projects components folder
Folder structure The components of a Frontend project are important. Because it makes developing and maintaining projects easier. Especially when dealing with large or complex components, organizing folders helps keep your code organized and easier to find and understand.
Here is the folder structure. components in various formats commonly used in projects developed using Next.js and TypeScript:
1. Atomic Design Structure
Atomic Design is a design concept that divides components according to their complexity and functionality. It is divided into 5 levels: Atoms, Molecules, Organisms, Templates, and Pages.
src/ └── components/ ├── atoms/ # Small, reusable elements (e.g., buttons, inputs) │ ├── Button.tsx │ ├── Input.tsx │ ├── Icon.tsx │ └── ... # Additional atoms │ ├── molecules/ # Combinations of atoms (e.g., form groups) │ ├── FormInput.tsx │ ├── NavLink.tsx │ └── ... # Additional molecules │ ├── organisms/ # Complex UI components (e.g., headers, cards) │ ├── Header.tsx │ ├── Card.tsx │ ├── Footer.tsx │ └── ... # Additional organisms │ ├── templates/ # Page templates (layouts with placeholders) │ ├── MainLayout.tsx │ ├── DashboardLayout.tsx │ └── ... # Additional templates │ └── pages/ # Page-specific components (used directly in pages) ├── HomePage.tsx ├── AboutPage.tsx └── ... # Additional page components
example:
Atoms: Button.tsx
import React from 'react'; interface ButtonProps { label: string; onClick: () => void; type?: 'button' | 'submit' | 'reset'; disabled?: boolean; } const Button: React.FC<ButtonProps> = ({ label, onClick, type = 'button', disabled = false }) => ( <button type={type} onClick={onClick} disabled={disabled} className="btn"> {label} </button> ); export default Button;
Molecules: FormInput.tsx
import React from 'react'; import Input from '../atoms/Input'; import Label from '../atoms/Label'; interface FormInputProps { label: string; value: string; onChange: (value: string) => void; } const FormInput: React.FC<FormInputProps> = ({ label, value, onChange }) => ( <div className="form-input"> <Label text={label} /> <Input value={value} onChange={onChange} /> </div> ); export default FormInput;
Organisms: Header.tsx
import React from 'react'; import NavLink from '../molecules/NavLink'; import Logo from '../atoms/Logo'; const Header: React.FC = () => ( <header className="header"> <Logo /> <nav> <NavLink href="/" label="Home" /> <NavLink href="/about" label="About" /> <NavLink href="/contact" label="Contact" /> </nav> </header> ); export default Header;
2. Feature-Based Structure
Structures that separate components by feature or module are popular in feature-rich projects. Helps manage and expand features efficiently
src/ └── components/ ├── authentication/ # Components related to authentication │ ├── Login.tsx │ ├── Signup.tsx │ └── PasswordReset.tsx │ ├── dashboard/ # Components specific to the dashboard │ ├── DashboardHeader.tsx │ ├── DashboardSidebar.tsx │ └── StatsCard.tsx │ ├── userProfile/ # Components for user profile │ ├── ProfileHeader.tsx │ ├── EditProfileForm.tsx │ └── Avatar.tsx │ ├── shared/ # Shared or common components across features │ ├── Button.tsx │ ├── Modal.tsx │ └── ... # Additional shared components │ └── layout/ # Layout components ├── Header.tsx ├── Footer.tsx └── Sidebar.tsx
example:
Authentication: Login.tsx
import React, { useState } from 'react'; import Button from '../shared/Button'; import FormInput from '../shared/FormInput'; const Login: React.FC = () => { const [email, setEmail] = useState(''); const [password, setPassword] = useState(''); const handleLogin = () => { // Logic for login }; return ( <div className="login"> <h2>Login</h2> <FormInput label="Email" value={email} onChange={setEmail} /> <FormInput label="Password" value={password} onChange={setPassword} /> <Button label="Login" onClick={handleLogin} /> </div> ); }; export default Login;
Dashboard: StatsCard.tsx
import React from 'react'; interface StatsCardProps { title: string; value: number; icon: React.ReactNode; } const StatsCard: React.FC<StatsCardProps> = ({ title, value, icon }) => ( <div className="stats-card"> <div className="stats-card-icon">{icon}</div> <div className="stats-card-info"> <h3>{title}</h3> <p>{value}</p> </div> </div> ); export default StatsCard;
3. Domain-Driven Structure
This structure focuses on organizing components according to the domain or bounded context of your project. This makes this structure suitable for complex systems that require clear domain separation
src/ └── components/ ├── domain/ │ ├── product/ # Components related to product domain │ │ ├── ProductCard.tsx │ │ ├── ProductList.tsx │ │ └── ProductDetail.tsx │ │ │ ├── cart/ # Components for cart domain │ │ ├── CartItem.tsx │ │ ├── CartSummary.tsx │ │ └── CartIcon.tsx │ │ │ ├── user/ # Components for user domain │ │ ├── UserAvatar.tsx │ │ ├── UserProfile.tsx │ │ └── UserSettings.tsx │ │ │ └── ... # Additional domain-specific components │ ├── ui/ # UI elements (atoms, molecules, etc.) │ ├── atoms/ │ ├── molecules/ │ └── organisms/ │ └── layout/ # Layout components ├── Header.tsx ├── Footer.tsx └── Sidebar.tsx
example:
Product: ProductCard.tsx
import React from 'react'; interface ProductCardProps { name: string; price: number; imageUrl: string; onAddToCart: () => void; } const ProductCard: React.FC<ProductCardProps> = ({ name, price, imageUrl, onAddToCart }) => ( <div className="product-card"> <img src={imageUrl} alt={name} className="product-card-image" /> <div className="product-card-info"> <h3>{name}</h3> <p>${price.toFixed(2)}</p> <button onClick={onAddToCart}>Add to Cart</button> </div> </div> ); export default ProductCard;
Cart: CartSummary.tsx
import React from 'react'; interface CartSummaryProps { totalItems: number; totalPrice: number; } const CartSummary: React.FC<CartSummary Props> = ({ totalItems, totalPrice }) => ( <div className="cart-summary"> <h3>Cart Summary</h3> <p>Total Items: {totalItems}</p> <p>Total Price: ${totalPrice.toFixed(2)}</p> <button>Checkout</button> </div> ); export default CartSummary;
4. Component-Driven Development (CDD) with Storybook
This structure is designed to support cross-platform development. Component-Driven Development (CDD) using Storybook which allows you to develop and test components in a format separate from the main application
src/ └── components/ ├── Button/ │ ├── Button.tsx # Component implementation │ ├── Button.stories.tsx # Storybook stories │ ├── Button.test.tsx # Unit tests │ └── Button.module.css # Component-specific styles │ ├── Input/ │ ├── Input.tsx │ ├── Input.stories.tsx │ ├── Input.test.tsx │ └── Input.module.css │ ├── Modal/ │ ├── Modal.tsx │ ├── Modal.stories.tsx │ ├── Modal.test.tsx │ └── Modal.module.css │ └── ... # Additional component folders
example:
Button: Button.tsx
import React from 'react'; import styles from './Button.module.css'; interface ButtonProps { label: string; onClick: () => void; variant?: 'primary' | 'secondary'; } const Button: React.FC<ButtonProps> = ({ label, onClick, variant = 'primary' }) => ( <button className={`${styles.btn} ${styles[variant]}`} onClick={onClick}> {label} </button> ); export default Button;
Button: Button.stories.tsx (Storybook)
import React from 'react'; import { Meta, Story } from '@storybook/react'; import Button, { ButtonProps } from './Button'; export default { title: 'Components/Button', component: Button, } as Meta; const Template: Story<ButtonProps> = (args) => <Button {...args} />; export const Primary = Template.bind({}); Primary.args = { label: 'Primary Button', onClick: () => console.log('Primary Button Clicked'), variant: 'primary', }; export const Secondary = Template.bind({}); Secondary.args = { label: 'Secondary Button', onClick: () => console.log('Secondary Button Clicked'), variant: 'secondary', };
5. Shared Component Library
In projects where multiple teams work together Creating a structure that uses common components is important. This structure emphasizes separating components that can be reused throughout the project
src/ └── components/ ├── shared/ # Shared components across the application │ ├── Button/ │ │ ├── Button.tsx │ │ └── Button.module.css │ │ │ ├── Modal/ │ │ ├── Modal.tsx │ │ └── Modal.module.css │ │ │ └── ... # Additional shared components │ ├── featureSpecific/ # Feature-specific components │ ├── UserProfile/ │ │ ├── ProfileHeader.tsx │ │ ├── ProfileDetails.tsx │ │ └── Avatar.tsx │ │ │ ├── ProductList/ │ │ ├── ProductCard.tsx │ │ └── ProductFilter.tsx │ │ │ └── ... # Additional feature-specific components │ └── layout/ # Layout components ├── Header.tsx ├── Footer.tsx └── Sidebar.tsx
ตัวอย่าง:
Shared: Modal.tsx
import React from 'react'; import styles from './Modal.module.css'; interface ModalProps { title: string; isOpen: boolean; onClose: () => void; } const Modal: React.FC<ModalProps> = ({ title, isOpen, onClose, children }) => { if (!isOpen) return null; return ( <div className={styles.modalOverlay}> <div className={styles.modal}> <h2>{title}</h2> <button className={styles.closeButton} onClick={onClose}> × </button> <div className={styles.modalContent}>{children}</div> </div> </div> ); }; export default Modal;
Feature-Specific: ProfileHeader.tsx
import React from 'react'; interface ProfileHeaderProps { name: string; bio: string; avatarUrl: string; } const ProfileHeader: React.FC<ProfileHeaderProps> = ({ name, bio, avatarUrl }) => ( <div className="profile-header"> <img src={avatarUrl} alt={name} className="profile-avatar" /> <h1>{name}</h1> <p>{bio}</p> </div> ); export default ProfileHeader;
Factors to Consider When Structuring Components
- Reusability: ควรแยก component ที่สามารถใช้ซ้ำได้ออกจาก component ที่เฉพาะเจาะจงกับฟีเจอร์
- Maintainability: การจัดโครงสร้างที่ดีช่วยให้การดูแลรักษาและการอัพเดตโปรเจคเป็นไปอย่างราบรื่น
- Scalability: โครงสร้างที่ดีจะช่วยให้การขยายฟีเจอร์และการเพิ่ม component ใหม่ ๆ เป็นเรื่องง่าย
- Performance: ใช้เทคนิคที่เหมาะสมในการโหลดและใช้ component เพื่อให้แน่ใจว่าแอปพลิเคชันของคุณมีประสิทธิภาพ
Best Practices for Component Structure
- Single Responsibility Principle: แต่ละ component ควรทำหน้าที่เดียวและทำได้ดี
- Component Naming: ตั้งชื่อ component ให้สื่อความหมายและชัดเจน
- Component Composition: ใช้ composition แทน inheritance เมื่อสร้าง component ใหม่
- Use Prop Types or TypeScript: กำหนด prop types หรือใช้ TypeScript interfaces เพื่อเพิ่มความปลอดภัยในการใช้งาน
- Write Tests: เขียน unit tests สำหรับ component ทุกตัวเพื่อตรวจสอบการทำงาน
ด้วยข้อมูลและแนวทางเหล่านี้ หวังว่าคุณจะสามารถจัดโครงสร้างในโฟลเดอร์ components ของโปรเจคได้อย่างมีประสิทธิภาพและเหมาะสมกับความต้องการของโปรเจคของคุณ!
The above is the detailed content of Organizing the Frontend projects components folder. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

Frequently Asked Questions and Solutions for Front-end Thermal Paper Ticket Printing In Front-end Development, Ticket Printing is a common requirement. However, many developers are implementing...

JavaScript is the cornerstone of modern web development, and its main functions include event-driven programming, dynamic content generation and asynchronous programming. 1) Event-driven programming allows web pages to change dynamically according to user operations. 2) Dynamic content generation allows page content to be adjusted according to conditions. 3) Asynchronous programming ensures that the user interface is not blocked. JavaScript is widely used in web interaction, single-page application and server-side development, greatly improving the flexibility of user experience and cross-platform development.

There is no absolute salary for Python and JavaScript developers, depending on skills and industry needs. 1. Python may be paid more in data science and machine learning. 2. JavaScript has great demand in front-end and full-stack development, and its salary is also considerable. 3. Influencing factors include experience, geographical location, company size and specific skills.

Discussion on the realization of parallax scrolling and element animation effects in this article will explore how to achieve similar to Shiseido official website (https://www.shiseido.co.jp/sb/wonderland/)...

Learning JavaScript is not difficult, but it is challenging. 1) Understand basic concepts such as variables, data types, functions, etc. 2) Master asynchronous programming and implement it through event loops. 3) Use DOM operations and Promise to handle asynchronous requests. 4) Avoid common mistakes and use debugging techniques. 5) Optimize performance and follow best practices.

The latest trends in JavaScript include the rise of TypeScript, the popularity of modern frameworks and libraries, and the application of WebAssembly. Future prospects cover more powerful type systems, the development of server-side JavaScript, the expansion of artificial intelligence and machine learning, and the potential of IoT and edge computing.

How to merge array elements with the same ID into one object in JavaScript? When processing data, we often encounter the need to have the same ID...

Explore the implementation of panel drag and drop adjustment function similar to VSCode in the front-end. In front-end development, how to implement VSCode similar to VSCode...
