DEV Community

nedajahanfar
nedajahanfar

Posted on

Introduction to React: Understanding the Basics-part.3

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:

  1. 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 <h1>Welcome to My App</h1>;
}

export function Footer() {
  return <footer>Footer content here</footer>;
}
Enter fullscreen mode Exit fullscreen mode

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';
Enter fullscreen mode Exit fullscreen mode
  1. 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 <h1>Welcome to My App</h1>;
}

Enter fullscreen mode Exit fullscreen mode

Define the function first and then use export default at the end of the file:

function Header() {
  return <h1>Welcome to My App</h1>;
}

export default Header;

Enter fullscreen mode Exit fullscreen mode

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';
Enter fullscreen mode Exit fullscreen mode

_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"]
}

Enter fullscreen mode Exit fullscreen mode

This will allow you to use absolute imports starting from the src/ folder.

Top comments (0)