Exporting and importing lets you share parts of your React app between files. It helps keep code organized and reusable.
0
0
Exporting and importing components in React
Introduction
When you want to use a button component in multiple pages.
When you split a big component into smaller pieces for easier management.
When you want to share utility components like headers or footers across your app.
When you want to keep your code clean by separating components into different files.
Syntax
React
export default ComponentName; // or export { ComponentName }; // Importing import ComponentName from './ComponentFile'; // or import { ComponentName } from './ComponentFile';
Default export means you export one main thing from a file.
Named export lets you export multiple things from one file.
Examples
This exports the Button component as the default export.
React
function Button() { return <button>Click me</button>; } export default Button;
This exports Header as a named export.
React
export function Header() { return <h1>Welcome</h1>; }
This imports the default export Button from the Button file.
React
import Button from './Button'; function App() { return <Button />; }
This imports the named export Header from the Header file.
React
import { Header } from './Header'; function App() { return <Header />; }
Sample Program
This example shows a Button component exported as default from Button.js. Then App.js imports and uses it inside a div with a heading.
React
/* Button.js */ import React from 'react'; export default function Button() { return <button>Click me</button>; } /* App.js */ import React from 'react'; import Button from './Button'; export default function App() { return ( <div> <h2>My App</h2> <Button /> </div> ); }
OutputSuccess
Important Notes
Always use the correct import style matching how the component was exported.
File paths in imports are relative and usually start with './' for the same folder.
Using default exports is simpler when you export one main component per file.
Summary
Exporting lets you share components between files.
Use default export for one main component, named export for multiple.
Import components with matching syntax to use them in your app.