日本語

How to Split React Components into Separate Files and Import Them

​​React​ES Modules,oxlint,TypeScript,Vite

To split a React component into a separate file, add export to the component in the new file, then use import in the file that uses it. If a file holds only one component, use export default. If it holds several, use named exports. That is the usual split (see the official docs on default vs. named exports). Whether you use { } in import depends on how the component was exported. This article shows how to do it when you want to tidy up a long App.tsx by moving parts such as cards and buttons into their own files.

Note

The test environment was Ubuntu 24.04 with Node.js 22.23.4. I tested in a project created from the react-ts template of npm create vite@latest, with React 19.3.1, Vite 8.3.8, @vitejs/plugin-react 6.3.0, TypeScript 7.0.2, and oxlint 1.93.0. I opened the page in Chromium, driven by Playwright 1.63.0. I did not test environments other than Vite, such as Next.js or webpack. I also did not test JavaScript-only projects (.jsx), ESLint configurations, or browsers other than Chromium.

Diagram with two boxes at the top, components/ProfileCard.tsx and components/Buttons.tsx, and one box below for App.tsx. ProfileCard.tsx contains "export default function ProfileCard". Buttons.tsx contains "export function PrimaryButton", "export function SecondaryButton", and "export type ButtonProps". Arrows run from each of these to App.tsx. App.tsx contains "import ProfileCard" and "import { PrimaryButton, SecondaryButton }", with braces.
The three files built in this article and how each export matches an import

Use export default when a file has only one component

Create src/components/ProfileCard.tsx with a single card component. Adding export default before the function makes it the default export of this file.

tsx
// default export: put only one main component in a file
type ProfileCardProps = {
  name: string;
  role: string;
};

export default function ProfileCard({ name, role }: ProfileCardProps) {
  return (
    <div className="card">
      <h2>{name}</h2>
      <p>{role}</p>
    </div>
  );
}

ProfileCardProps, the props type, is not exported. If a type is used only inside this file, you do not need to export it.

Use named exports when a file has several components

A file can have only one export default, but it can have any number of named exports (see the official docs on default vs. named exports). For src/components/Buttons.tsx, which contains two kinds of buttons, just add export before each function. The props type ButtonProps is also exported so other files can use it.

tsx
// Named exports: export multiple components and types from one file
export type ButtonProps = {
  label: string;
  onClick: () => void;
};

export function PrimaryButton({ label, onClick }: ButtonProps) {
  return (
    <button type="button" className="primary" onClick={onClick}>
      {label}
    </button>
  );
}

export function SecondaryButton({ label, onClick }: ButtonProps) {
  return (
    <button type="button" className="secondary" onClick={onClick}>
      {label}
    </button>
  );
}

On the importing side, match the braces to the export style

In src/App.tsx, import both files. The default export is imported without { }, and the named exports are imported inside { }. The path after from is relative to App.tsx.

tsx
import { useState } from 'react';
import ProfileCard from './components/ProfileCard';
import { PrimaryButton, SecondaryButton } from './components/Buttons';

export default function App() {
  const [count, setCount] = useState(0);

  return (
    <main>
      <ProfileCard name="ねこ" role="フロントエンド担当" />
      <p id="count">いいね {count} 件</p>
      <PrimaryButton label="いいね" onClick={() => setCount((c) => c + 1)} />
      <SecondaryButton label="リセット" onClick={() => setCount(0)} />
    </main>
  );
}

In the test environment, npx tsc -b reported no type errors, and npx vite build also succeeded as-is. When I opened the page in the dev server, it showed the card with ねこ (neko, "cat") and フロントエンド担当 (frontend), いいね 0 件 (0 likes), and the two buttons.

When you import a default export, you can name it whatever you like after import. A named import must use the same name as the export (see the official docs, which include a table of export and import syntax and an explanation).

Both forms worked whether or not the from path had a file extension. The template's main.tsx uses import App from './App.tsx' with the extension. When I changed the import in App.tsx to './components/ProfileCard.tsx', tsc and vite build still passed. tsc accepts this because the template's tsconfig.app.json enables allowImportingTsExtensions. This option is a TypeScript setting that allows imports with .ts or .tsx extensions (see the TypeScript docs for allowImportingTsExtensions).

If you forget export, the page shows nothing in the dev server

I removed export from SecondaryButton in Buttons.tsx. tsc then reported the following errors.

text
src/App.tsx(3,25): error TS2459: Module '"./components/Buttons"' declares 'SecondaryButton' locally, but it is not exported.
src/components/Buttons.tsx(15,10): error TS6133: 'SecondaryButton' is declared but its value is never read.

The first line means that SecondaryButton is declared in Buttons but not exported. The second means that SecondaryButton is no longer exported and is not used anywhere in its file. npx vite build also stopped with [MISSING_EXPORT] "SecondaryButton" is not exported by "src/components/Buttons.tsx".

The real problem appears when you open the page in the dev server (npm run dev). The page showed nothing, and the contents of <div id="root"> were empty. Errors appeared both in the browser and in the dev server terminal. This is the line in the terminal:

text
SyntaxError: The requested module '/src/components/Buttons.tsx' does not provide an export named 'SecondaryButton'

The Vite dev server only converts .ts and .tsx files to JavaScript. It does not check types (see the Vite docs on transpile-only). After you split files, check for type errors in your editor or with npx tsc -b. The template's npm run build runs tsc -b first.

Add type when importing a type

When you import a type such as ButtonProps in the same { } as components, put type before its name. I tested what happens without it. Inside App, ButtonProps is used as the type of the variable likeProps.

tsx
// Mistake: the ButtonProps type is not given a type
import { PrimaryButton, SecondaryButton, ButtonProps } from './components/Buttons';

// Inside App
const likeProps: ButtonProps = { label: 'いいね', onClick: () => setCount((c) => c + 1) };
// Inside JSX
<PrimaryButton {...likeProps} />

tsc reported this error:

text
src/App.tsx(3,42): error TS1484: 'ButtonProps' is a type and must be imported using a type-only import when 'verbatimModuleSyntax' is enabled.

The template's tsconfig.app.json enables verbatimModuleSyntax. With this setting, an import without type stays in the JavaScript output even when it is used only as a type (see the TypeScript docs for verbatimModuleSyntax). A type does not exist in JavaScript, so the page showed nothing in the dev server, just as when export was missing. The browser error was does not provide an export named 'ButtonProps'.

When I changed the import line as follows (leaving the two lines for likeProps unchanged), the tsc error disappeared and the page displayed.

tsx
import { PrimaryButton, SecondaryButton, type ButtonProps } from './components/Buttons';

Group imports with index.ts in the folder

As the components folder grows, the import lines in App.tsx grow too. If you put an index.ts in the folder and re-export each file's exports from it, the users of the folder only need to name the folder once.

ts
// Entry point of the components folder: re-export the exports of other files together
export { default as ProfileCard } from './ProfileCard';
export { PrimaryButton, SecondaryButton, type ButtonProps } from './Buttons';

Re-export the default export with a name, using default as ProfileCard. Importers then receive everything inside { }.

tsx
import { ProfileCard, PrimaryButton, SecondaryButton } from './components';

In the test environment, from './components' loaded components/index.ts. There were no tsc errors, and the page displayed the same way.

Put non-component functions in a separate file

In the test environment, when I edited and saved a file that exported only components, the screen updated and the state was kept (Fast Refresh). However, when I also exported an ordinary function such as formatCount from the same file, the state was sometimes lost on save. This mechanism works only when the file exports only components (see the README of @vitejs/plugin-react, "Consistent components exports").

tsx
// Export non-component functions from the same file too
export function formatCount(count: number) {
  return `いいね ${count} 件`;
}

I tested adding this function to the end of Buttons.tsx, and also to the end of App.tsx, which holds the state. In each case I pressed the like button three times to show いいね 3 件 (3 likes), then edited and saved the file. The results are below.

Edited file What it exports Display after saving
Buttons.tsx Components only いいね 3 件 (3 likes) stayed, and the edit was reflected
Buttons.tsx Components and formatCount いいね 3 件 (3 likes) stayed, and the edit was reflected
App.tsx Components only いいね 3 件 (3 likes) stayed, and the edit was reflected
App.tsx Components and formatCount The whole page reloaded and went back to いいね 0 件 (0 likes)

In both cases where I added formatCount, the dev server terminal printed Could not Fast Refresh ("formatCount" export is incompatible). In the Buttons.tsx case, it then printed hmr update /src/App.tsx. As the README says, the update reached App.tsx, which imports Buttons.tsx. The count state is held by App, and it was kept. In the App.tsx case, the terminal printed page reload src/App.tsx, and the whole page reloaded.

The template's oxlint configuration includes the react/only-export-components rule, which detects this pattern. When I ran npx oxlint, it warned on the formatCount line:

text
src/components/Buttons.tsx:24:17: warning react(only-export-components): Fast refresh only works when a file only exports components. Use a new file to share constants or functions between components.
Point

From a component file, export only components (and types). Put functions shared by several components in a separate file, such as format.ts.

​Posted by 86