5. How to Import and Export React Components
๐ฆ Importing and Exporting Components in React
Why Import & Export?
-
Allows you to reuse components across different files.
-
Keeps your project organized and modular.
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
- Usually, youโll import components into your main (root) file, often called
App.jsx.
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.