0
0
ReactHow-ToBeginner · 3 min read

How to Export Component in React: Syntax and Examples

In React, you export a component using either export default for a single main export or export for named exports. Use export default ComponentName; to export one component per file, or export { ComponentName }; to export multiple components from the same file.
📐

Syntax

There are two main ways to export components in React:

  • Default export: Exports one main component per file. Import without curly braces.
  • Named export: Exports one or more components by name. Import using curly braces.

Example syntax:

export default ComponentName;

// or

export { ComponentName };
jsx
function MyComponent() {
  return <div>Hello</div>;
}

export default MyComponent;

// or

function AnotherComponent() {
  return <div>World</div>;
}

export { AnotherComponent };
💻

Example

This example shows a React component exported as default and imported in another file to render on the page.

jsx
// File: Greeting.js
import React from 'react';

function Greeting() {
  return <h1>Hello, React!</h1>;
}

export default Greeting;

// File: App.js
import React from 'react';
import Greeting from './Greeting';

function App() {
  return (
    <main>
      <Greeting />
    </main>
  );
}

export default App;
Output
<h1>Hello, React!</h1>
⚠️

Common Pitfalls

Common mistakes when exporting React components include:

  • Mixing default and named exports incorrectly.
  • Importing a default export with curly braces or named exports without them.
  • Forgetting to export the component at all.

Always match the export and import style.

jsx
// Wrong: importing default export with braces
import { Greeting } from './Greeting'; // ❌

// Correct: import default export without braces
import Greeting from './Greeting'; // ✅

// Wrong: exporting component without export keyword
function Hello() {
  return <div>Hi</div>;
}
// Forgot export here ❌

// Correct: export component
export function Hello() {
  return <div>Hi</div>;
}
📊

Quick Reference

Export TypeSyntaxImport SyntaxUse Case
Default Exportexport default ComponentName;import ComponentName from './file';Single main component per file
Named Exportexport { ComponentName };import { ComponentName } from './file';Multiple components per file

Key Takeaways

Use export default to export one main component per file and import it without braces.
Use named exports with export { ComponentName } to export multiple components and import with braces.
Match your import style exactly to the export type to avoid errors.
Always export your component to use it in other files.
Default exports simplify imports when only one component is exported.