5. How to Import and Export React Components

๐Ÿ“ฆ Importing and Exporting Components in React

Why Import & Export?

Example Component: Cat.jsx

function Cat() {
return (
<div className="card">
<h2>Mr. Whiskers</h2>
<img
src="https://cdn.freecodecamp.org/curriculum/cat-photo-app/running-cats.jpg"
alt="Tuxedo cats running on dirt ground."
/>
</div>
);
}

๐Ÿ”น Exporting a Component

1. Export at the end of the file:

export default Cat;

2. Or export directly:

export default function Cat() {
return (
<div className="card">
<h2>Mr. Whiskers</h2>
<img
src="https://cdn.freecodecamp.org/curriculum/cat-photo-app/running-cats.jpg"
alt="Tuxedo cats running on dirt ground."
/>
</div>
);
}

๐Ÿ“ default means this is the main export from the file.
Each file can only have one default export.

๐Ÿ”น Importing a Component

Example:

import Cat from "./Cat";

export default function App() {
return <Cat />;
}

๐Ÿ’ก The "./Cat" path means the file is in the same folder as App.jsx.

๐Ÿง  Key Takeaways

โœ… Use .jsx files for components that contain JSX code.
โœ… Use export default to share a component from one file.
โœ… Use import to bring that component into another file.
โœ… You can compose multiple components together to build complex UIs.