search
HomeWeb Front-endJS TutorialOrganizing the Frontend project&#s components folder

Organizing the Frontend project

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 classname="btn">
    {label}
  </button>
);

export default Button;
</buttonprops>

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}"></label>
    <input value="{value}" onchange="{onChange}">
  </div>
);

export default FormInput;
</forminputprops>

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></logo>
    <nav>
      <navlink href="/" label="Home"></navlink>
      <navlink href="/about" label="About"></navlink>
      <navlink href="/contact" label="Contact"></navlink>
    </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 id="Login">Login</h2>
      <forminput label="Email" value="{email}" onchange="{setEmail}"></forminput>
      <forminput label="Password" value="{password}" onchange="{setPassword}"></forminput>
      <button label="Login" onclick="{handleLogin}"></button>
    </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 id="title">{title}</h3>
      <p>{value}</p>
    </div>
  </div>
);

export default StatsCard;
</statscardprops>

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="%7BimageUrl%7D" alt="{name}" classname="product-card-image">
    <div classname="product-card-info">
      <h3 id="name">{name}</h3>
      <p>${price.toFixed(2)}</p>
      <button onclick="{onAddToCart}">Add to Cart</button>
    </div>
  </div>
);

export default ProductCard;
</productcardprops>

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 id="Cart-Summary">Cart Summary</h3>
    <p>Total Items: {totalItems}</p>
    <p>Total Price: ${totalPrice.toFixed(2)}</p>
    <button>Checkout</button>
  </div>
);

export default CartSummary;
</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}" onclick="{onClick}">
    {label}
  </button>
);

export default Button;
</buttonprops>

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></button>;

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',
};
</buttonprops>

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 id="title">{title}</h2>
        <button classname="{styles.closeButton}" onclick="{onClose}">
          ×
        </button>
        <div classname="{styles.modalContent}">{children}</div>
      </div>
    </div>
  );
};

export default Modal;
</modalprops>

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="%7BavatarUrl%7D" alt="{name}" classname="profile-avatar">
    <h1 id="name">{name}</h1>
    <p>{bio}</p>
  </div>
);

export default ProfileHeader;
</profileheaderprops>

Factors to Consider When Structuring Components

  1. Reusability: ควรแยก component ที่สามารถใช้ซ้ำได้ออกจาก component ที่เฉพาะเจาะจงกับฟีเจอร์
  2. Maintainability: การจัดโครงสร้างที่ดีช่วยให้การดูแลรักษาและการอัพเดตโปรเจคเป็นไปอย่างราบรื่น
  3. Scalability: โครงสร้างที่ดีจะช่วยให้การขยายฟีเจอร์และการเพิ่ม component ใหม่ ๆ เป็นเรื่องง่าย
  4. 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 project&#s components folder. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Replace String Characters in JavaScriptReplace String Characters in JavaScriptMar 11, 2025 am 12:07 AM

Detailed explanation of JavaScript string replacement method and FAQ This article will explore two ways to replace string characters in JavaScript: internal JavaScript code and internal HTML for web pages. Replace string inside JavaScript code The most direct way is to use the replace() method: str = str.replace("find","replace"); This method replaces only the first match. To replace all matches, use a regular expression and add the global flag g: str = str.replace(/fi

Custom Google Search API Setup TutorialCustom Google Search API Setup TutorialMar 04, 2025 am 01:06 AM

This tutorial shows you how to integrate a custom Google Search API into your blog or website, offering a more refined search experience than standard WordPress theme search functions. It's surprisingly easy! You'll be able to restrict searches to y

Build Your Own AJAX Web ApplicationsBuild Your Own AJAX Web ApplicationsMar 09, 2025 am 12:11 AM

So here you are, ready to learn all about this thing called AJAX. But, what exactly is it? The term AJAX refers to a loose grouping of technologies that are used to create dynamic, interactive web content. The term AJAX, originally coined by Jesse J

Example Colors JSON FileExample Colors JSON FileMar 03, 2025 am 12:35 AM

This article series was rewritten in mid 2017 with up-to-date information and fresh examples. In this JSON example, we will look at how we can store simple values in a file using JSON format. Using the key-value pair notation, we can store any kind

8 Stunning jQuery Page Layout Plugins8 Stunning jQuery Page Layout PluginsMar 06, 2025 am 12:48 AM

Leverage jQuery for Effortless Web Page Layouts: 8 Essential Plugins jQuery simplifies web page layout significantly. This article highlights eight powerful jQuery plugins that streamline the process, particularly useful for manual website creation

What is 'this' in JavaScript?What is 'this' in JavaScript?Mar 04, 2025 am 01:15 AM

Core points This in JavaScript usually refers to an object that "owns" the method, but it depends on how the function is called. When there is no current object, this refers to the global object. In a web browser, it is represented by window. When calling a function, this maintains the global object; but when calling an object constructor or any of its methods, this refers to an instance of the object. You can change the context of this using methods such as call(), apply(), and bind(). These methods call the function using the given this value and parameters. JavaScript is an excellent programming language. A few years ago, this sentence was

Improve Your jQuery Knowledge with the Source ViewerImprove Your jQuery Knowledge with the Source ViewerMar 05, 2025 am 12:54 AM

jQuery is a great JavaScript framework. However, as with any library, sometimes it’s necessary to get under the hood to discover what’s going on. Perhaps it’s because you’re tracing a bug or are just curious about how jQuery achieves a particular UI

10 Mobile Cheat Sheets for Mobile Development10 Mobile Cheat Sheets for Mobile DevelopmentMar 05, 2025 am 12:43 AM

This post compiles helpful cheat sheets, reference guides, quick recipes, and code snippets for Android, Blackberry, and iPhone app development. No developer should be without them! Touch Gesture Reference Guide (PDF) A valuable resource for desig

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version