SyntaxStudy
Sign Up
React Splitting Components and File Organisation
React Beginner 1 min read

Splitting Components and File Organisation

As a React application grows, keeping every component in a single file becomes unmanageable. The standard practice is one component per file, named to match the component, with a `.jsx` (or `.tsx` for TypeScript) extension. Components are exported with `export default` and imported wherever they are needed. Named exports are common for utility functions and smaller helper components co-located in the same file. A common folder structure groups components by feature or by type. A feature-based layout puts all files related to a feature — component, styles, tests, hooks — into one directory. A type-based layout separates `components/`, `pages/`, `hooks/`, and `utils/` at the top level. Neither is universally superior; the key is consistency within a project. Index files (`index.js`) are sometimes used to re-export multiple components from a directory, creating a cleaner public API for a feature module. Barrel exports can simplify imports but also hinder tree-shaking in some bundlers, so use them with awareness. Keeping components small — ideally under 100 lines of JSX — and extracting sub-components into their own files makes code reviews easier and helps the bundler optimise code splitting.
Example
// ── src/components/ui/Button.jsx ─────────────────────────────
const VARIANTS = {
  primary: { background: '#3b82f6', color: '#fff' },
  secondary: { background: '#e5e7eb', color: '#111' },
  danger: { background: '#ef4444', color: '#fff' },
};

function Button({ children, variant = 'primary', onClick, disabled = false }) {
  return (
    <button
      style={{ ...VARIANTS[variant], padding: '8px 16px', borderRadius: 6, border: 'none', cursor: disabled ? 'not-allowed' : 'pointer', opacity: disabled ? 0.6 : 1 }}
      onClick={onClick}
      disabled={disabled}
    >
      {children}
    </button>
  );
}

export default Button;

// ── src/components/ui/index.js (barrel export) ───────────────
// export { default as Button } from './Button';
// export { default as Card }   from './Card';
// export { default as Input }  from './Input';

// ── src/pages/HomePage.jsx ───────────────────────────────────
// import { Button, Card } from '../components/ui';
//
// function HomePage() {
//   return (
//     <Card title="Welcome">
//       <Button onClick={() => alert('clicked')}>Get Started</Button>
//       <Button variant="secondary">Learn More</Button>
//     </Card>
//   );
// }
//
// export default HomePage;