This document establishes MANDATORY architectural principles and dependencies for all React feature development. Deviation from these guidelines requires explicit approval.
- ALWAYS analyze existing codebase patterns before writing ANY code
- FOLLOW established architectural patterns exactly (use rup-data as template)
- UNDERSTAND shared components and their usage patterns
- STUDY the existing API integration patterns
- MAINTAIN architectural consistency across all features
- REUSE existing patterns and components
- AVOID creating new approaches when existing ones work
- FOLLOW the established folder structure and naming conventions
{
"@heroui/react": "^2.7.11",
"tailwindcss": "latest",
"lucide-react": "^0.525.0",
"framer-motion": "^12.19.2"
}Rules:
- HeroUI v2.7.11: The ONLY UI library allowed
- Components: Button, Input, Modal, Table, Card, Chip, Select, etc.
- Tailwind CSS: For ALL styling and responsive design
- Lucide React: For ALL icons (no other icon libraries)
- Framer Motion: For animations (already integrated with HeroUI)
Example Usage:
import { Button, Input, Modal, ModalContent } from '@heroui/react';
import { Search, Plus, Edit, Trash2 } from 'lucide-react';{
"react-router-dom": "^6.30.1"
}Rules:
- React Router DOM v6: The only routing solution
- Pattern: Feature-based routing with nested layouts
- Structure: All routes MUST go through AppLayout wrapper
Example Structure:
// App.tsx
<Route path="/" element={<AppLayout />}>
<Route path="feature-name" element={<FeaturePage />} />
</Route>
// AppLayout.tsx navigation
<Link to="/feature-name" className="block p-2 rounded hover:bg-gray-700">
Feature Name
</Link>{
"axios": "^1.10.0"
}Rules:
- Axios: Direct axios calls (NO shared API client)
- Pattern: Follow exact rup-data API structure
- Error Handling: Comprehensive logging and user-friendly messages
- Timeout: 30-second standard for all requests
Example Pattern:
// api.ts
import axios from 'axios';
const buildApiUrl = (endpoint: string) => {
return `${BASE_URL}${endpoint}`;
};
export async function fetchData(): Promise<DataType[]> {
try {
const url = buildApiUrl('/endpoint');
console.log('π Fetching data from:', url);
const response = await axios.get<DataType[]>(url, {
timeout: 30000,
headers: {
'Content-Type': 'application/json',
'Accept': 'application/json',
}
});
console.log('β
Response received:', {
status: response.status,
dataLength: response.data.length
});
return response.data;
} catch (error: any) {
console.error('β API Error details:', {
message: error.message,
status: error.response?.status,
responseData: error.response?.data
});
throw new Error(`Failed to fetch data: ${error.message}`);
}
}Rules:
- React Hooks: Custom hooks for each feature
- Pattern:
useFeatureName()hook structure - NO: Redux, Zustand, or global state libraries without approval
- Local State: useState for component-level state
Example Pattern:
// hooks.ts
export function useFeatureData(params: SearchParams = {}) {
const [data, setData] = useState<DataType[]>([]);
const [loading, setLoading] = useState(true);
const [error, setError] = useState<string>('');
const loadData = async () => {
try {
setLoading(true);
setError('');
const result = await fetchData(params);
setData(result);
} catch (err) {
setError(err instanceof Error ? err.message : 'An error occurred');
} finally {
setLoading(false);
}
};
useEffect(() => {
loadData();
}, [params]);
return { data, loading, error, refetch: loadData };
}Rules:
- Full Type Safety: All interfaces must be defined
- Import Types: Use
import typefor type-only imports - Generic Components: Type-safe generic components where needed
- Strict Mode: Follow existing tsconfig.json settings
Example Pattern:
// types.ts
export interface DataItem {
id: number;
name: string;
description: string;
// ... other properties
}
export interface ApiResponse {
data: DataItem[];
total: number;
page: number;
}
// Component with proper typing
import type { DataItem } from './types';
interface ComponentProps {
items: DataItem[];
onSelect: (item: DataItem) => void;
loading?: boolean;
}src/
βββ features/
β βββ [feature-name]/
β βββ README.md
β βββ types.ts
β βββ api.ts
β βββ hooks.ts
β βββ FeaturePage.tsx
β βββ components/
β βββ FeatureForm.tsx
β βββ FeatureModal.tsx
βββ components/
β βββ shared/
β βββ DataTable/
β βββ PageHeader/
β βββ ConfirmationDialog/
β βββ Toast/
βββ app/
βββ layout/
βββ AppLayout.tsx
Rules:
- PascalCase: For all component files
- camelCase: For utility functions and variables
- Descriptive Names: Clear, self-documenting names
- Single Responsibility: One component per file
Example:
// FeaturePage.tsx
export const FeaturePage: React.FC = () => {
// Component logic
};
// components/FeatureForm.tsx
interface FeatureFormProps {
isOpen: boolean;
onClose: () => void;
onSave: (data: FormData) => void;
}
export const FeatureForm: React.FC<FeatureFormProps> = ({
isOpen,
onClose,
onSave
}) => {
// Form logic
};MUST USE existing shared components:
// Required imports for common patterns
import { PageHeader } from '../../components/shared/PageHeader/PageHeader';
import { DataTable } from '../../components/shared/DataTable/DataTable';
import { ConfirmationDialog } from '../../components/shared/ConfirmationDialog';
import { useToast } from '../../components/shared/Toast';- HeroUI Components: Input, Textarea, Select, etc.
- Validation: Manual validation (no form libraries without approval)
- Error Display: Inline error messages with isInvalid prop
- Loading States: isLoading prop for submit buttons
const [formData, setFormData] = useState<FormData>({
name: '',
description: ''
});
const [errors, setErrors] = useState<Record<string, string>>({});
const validateForm = () => {
const newErrors: Record<string, string> = {};
if (!formData.name.trim()) {
newErrors.name = 'Name is required';
}
setErrors(newErrors);
return Object.keys(newErrors).length === 0;
};
const handleSubmit = () => {
if (!validateForm()) return;
onSave(formData);
};
// In JSX
<Input
label="Name"
value={formData.name}
onChange={(e) => setFormData(prev => ({ ...prev, name: e.target.value }))}
errorMessage={errors.name}
isInvalid={!!errors.name}
isRequired
/>- DataTable: Use existing shared DataTable component
- Pagination: External pagination with HeroUI Pagination
- Loading States: Spinner components for all async operations
- Error Handling: Retry mechanisms and user feedback
const columns = [
{ key: 'name', label: 'Name', sortable: true },
{ key: 'description', label: 'Description', sortable: false },
{ key: 'actions', label: 'Actions', sortable: false }
];
const renderCell = (item: DataItem, columnKey: string) => {
switch (columnKey) {
case 'name':
return <span className="font-medium">{item.name}</span>;
case 'actions':
return (
<div className="flex gap-2">
<Button size="sm" onPress={() => handleEdit(item)}>
<Edit className="w-4 h-4" />
</Button>
</div>
);
default:
return <span>{String(item[columnKey as keyof DataItem])}</span>;
}
};
<DataTable
data={data}
columns={columns}
loading={loading}
error={error}
onRetry={refetch}
renderCell={renderCell}
/>- Toast System: Use shared Toast component for notifications
- Confirmation Dialogs: Use shared ConfirmationDialog
- Loading States: isLoading prop for buttons and forms
- Error Messages: User-friendly error messages
// Toast notifications
const { success, error: showError, ToastContainer } = useToast();
const handleAction = async () => {
try {
await performAction();
success('Action completed successfully');
} catch (err) {
showError('Failed to complete action');
}
};
// In JSX
<ToastContainer />
// Confirmation dialog
<ConfirmationDialog
isOpen={isDeleteOpen}
onClose={onDeleteClose}
onConfirm={handleConfirmDelete}
title="Delete Item"
message="Are you sure you want to delete this item?"
confirmText="Delete"
isLoading={loading}
/>- UI Libraries: Material-UI, Ant Design, Chakra UI, etc.
- HTTP Clients: fetch API, different axios patterns
- State Management: Redux, Zustand, Context API for global state
- Routing: Reach Router, Next.js Router, etc.
- Icons: react-icons, heroicons, font-awesome, etc.
- Forms: Formik, React Hook Form, etc.
- Styling: styled-components, emotion, etc.
- Testing: Jest, React Testing Library (without approval)
- Creating new API client wrappers
- Custom HTTP interceptors
- Global state management without approval
- Custom UI component libraries
- Alternative folder structures
- Different naming conventions
- π New dependencies outside the core stack
- π Alternative state management solutions
- π Additional form/validation libraries
- π New HTTP client patterns
- π Alternative styling approaches
- π Testing frameworks and libraries
- π Build tools and bundlers
- π Alternative TypeScript configurations
- Research: Document why existing solution doesn't work
- Proposal: Present alternative with clear benefits
- Impact Assessment: Analyze effect on existing codebase
- Implementation Plan: Detailed migration strategy
- Testing Strategy: How to ensure no regressions
// MUST use TodoWrite tool for ALL tasks
const todos = [
{ id: "1", content: "Research existing patterns", status: "pending", priority: "high" },
{ id: "2", content: "Implement feature structure", status: "pending", priority: "medium" }
];- π Create Todo List: Use TodoWrite tool
- π Research Phase: Analyze existing patterns
- ποΈ Structure Setup: Create folder structure
- π» Implementation: Follow established patterns
- π§ͺ Testing: npm run dev and npm run build
- π Documentation: README.md for feature
# MUST run these commands during development
npm run dev # Test in development
npm run build # Check TypeScript compilation- β Follows existing architectural patterns
- β Uses approved dependencies only
- β Proper TypeScript typing
- β Error handling implemented
- β Loading states for all async operations
- β Responsive design with Tailwind
- β Proper component structure
- β Documentation updated
- β Functional: All requirements implemented
- β Consistent: Follows established patterns
- β Tested: Development server runs without errors
- β Compiled: TypeScript build succeeds
- β Documented: README.md created
- β Accessible: Proper ARIA labels and keyboard navigation
- β Responsive: Works on mobile and desktop
- β Error Handling: Comprehensive error management
Use src/features/sample-complete-api/ as the gold standard reference for:
- β Folder structure
- β API integration patterns
- β Component architecture
- β TypeScript usage
- β Error handling
- β User feedback
- β Documentation
src/features/sample-complete-api/
βββ README.md # Feature documentation
βββ types.ts # TypeScript interfaces
βββ api.ts # API integration
βββ hooks.ts # Custom hooks
βββ SampleCompletePage.tsx # Main component
βββ components/
βββ ProductForm.tsx # Form modal
βββ ProductDetailModal.tsx # Detail modal
- π STOP: Immediately halt development
- π Document: Record what was violated and why
- π Assess: Evaluate impact on existing codebase
- π Propose: Submit formal proposal for approval
- β³ Wait: Do not proceed until approval received
- Adding new dependencies without approval
- Creating custom API clients
- Using different UI patterns
- Ignoring TypeScript errors
- Skipping error handling
- Not following folder structure
- β Use pagination for large datasets
- β Implement proper loading states
- β Optimize images with fallbacks
- β Use React.memo for expensive components
- β Validate all user inputs
- β Sanitize API responses
- β Handle authentication properly
- β Use proper CORS settings
- β Write self-documenting code
- β Use meaningful variable names
- β Keep components small and focused
- β Follow single responsibility principle
- β Provide immediate feedback
- β Show loading states
- β Handle errors gracefully
- β Maintain responsive design
- README.md: For each feature
- TypeScript Interfaces: For all data structures
- Component Props: For all components
- API Documentation: For all endpoints
- Error Handling: For all error cases
# Feature Name
## Features
- List all implemented features
## API Endpoints
- Document all API calls
## Components
- List all components and their purpose
## Usage
- Provide usage examples
## Configuration
- List any configuration options
## Troubleshooting
- Common issues and solutionsπ This document serves as the definitive guide for all React feature development. Adherence to these guidelines ensures code quality, maintainability, and architectural consistency.
Last Updated: [Current Date] Version: 1.0.0 Status: Active