Back
๐Ÿ“œRulecursor

React Component Generator Rule

A Cursor/Copilot rule for generating consistent, accessible React components with proper TypeScript typing and testing patterns.

by ReactArchitectยท20 days agoยท
reactcomponentstypescriptaccessibilitytesting
# React Component Generation Rule

When creating React components, ALWAYS follow this structure:

## File Structure
For each component, create:
- `ComponentName.tsx` โ€” the component
- `ComponentName.test.tsx` โ€” unit tests (if complex enough)

## Component Template

```tsx
import { forwardRef } from "react"
import { cn } from "@/lib/utils"

interface ComponentNameProps {
  /** Description of what this prop controls */
  variant?: "default" | "secondary" | "destructive"
  /** Whether the component is disabled */
  disabled?: boolean
  /** Additional CSS classes */
  className?: string
  /** Child elements */
  children: React.ReactNode
}

/**
 * ComponentName - Brief description of what it does
 * 
 * @example
 * <ComponentName variant="default">Click me</ComponentName>
 */
const ComponentName = forwardRef<HTMLDivElement, ComponentNameProps>(
  ({ variant = "default", disabled = false, className, children, ...props }, ref) => {
    return (
      <div
        ref={ref}
        className={cn(
          "base-styles-here",
          variant === "secondary" && "secondary-styles",
          variant === "destructive" && "destructive-styles",
          disabled && "opacity-50 pointer-events-none",
          className
        )}
        aria-disabled={disabled}
        {...props}
      >
        {children}
      </div>
    )
  }
)
ComponentName.displayName = "ComponentName"
export { ComponentName }
export type { ComponentNameProps }
```

## Rules:
1. Always use `forwardRef` for components that wrap DOM elements
2. Always spread `...props` for HTML attribute passthrough
3. Use `cn()` for conditional classes, never template literals
4. Export both component and props type
5. JSDoc comment with @example on every component
6. All interactive elements must have aria labels
7. Support disabled state
8. Use semantic HTML elements (button, nav, article, etc.)