Exporting and Importing Components in React
In React, you have two ways to export components: named export and default export. Let’s break down both methods:
- Named Export: With named export, you can export multiple components from a single file. The syntax is straightforward: you need to use the export keyword before the component name.
export function Header() {
return Welcome to My App;
}
export function Footer() {
return Footer content here;
}
To import these components into another file, you’ll use curly braces {} and specify the exact name of the function, You can import multiple components from the same file by separating them with commas.
import { Header, Footer } from './components/Header';
- default export: With default export, you can only export one component (or function) per file. The syntax involves using export default.
The placement of export default is flexible, meaning you can either:
Use export default directly with the function definition:
export default function Header() {
return Welcome to My App;
}
Define the function first and then use export default at the end of the file:
function Header() {
return Welcome to My App;
}
export default Header;
To import a component that was exported as default, you don’t use curly braces. Instead, you can give the imported component any name you want:
import Header from './components/Header';
_You can also combine both named export and default export in a single file, but you can only have one default export per file.
_
Absolute Imports:
A relative path is a way of specifying the location of a file or directory in relation to the current working directory or file you're working in, In a typical React project, imports are written with relative paths, This can get messy as the app grows, especially with deep folder structures. Absolute imports solve this problem by allowing you to import files as if they were in the same folder, no matter where they are located in the project.
To enable absolute imports in React, you'll need to set it up manually. By default, React does not support absolute imports out-of-the-box. Here’s how you can set it up in a Create React App project:
In the root of your project, create or modify the jsconfig.json file to include this:
{
"compilerOptions": {
"baseUrl": "src"
},
"include": ["src"]
}
This will allow you to use absolute imports starting from the src/ folder.