In React, ES6 modules are used to organize and import/export code across different files or components. ES6 modules provide a standardized way to structure and share code in modern JavaScript applications. Here’s how you can use ES6 modules in React:
- Exporting:
To make a component or function available for use in other files, you can export it using theexport
keyword.
// MyComponent.js
export const MyComponent = () => {
// Component implementation
};
export const myFunction = () => {
// Function implementation
};
- Default Export:
You can also export a default component or function from a file. This is useful when you want to have a single default export per file.
// MyDefaultComponent.js
const MyDefaultComponent = () => {
// Component implementation
};
export default MyDefaultComponent;
- Importing:
To use the exported components or functions in another file, you can import them using theimport
keyword.
// OtherComponent.js
import { MyComponent, myFunction } from './MyComponent';
// Use MyComponent and myFunction in this file
If you are importing a default export, you can give it any name you prefer during the import.
// OtherDefaultComponent.js
import MyDefaultComponent from './MyDefaultComponent';
// Use MyDefaultComponent in this file
- Renaming Imports:
You can also rename the imported components or functions during the import.
// OtherComponent.js
import { MyComponent as CustomComponent } from './MyComponent';
// Use CustomComponent in this file
This can be useful to avoid naming conflicts or provide more descriptive names.
ES6 modules provide a clean and organized way to structure and share code in React applications. They allow you to import and export components, functions, or variables across different files, making your code modular and maintainable.