React Import & Export Explains
1. Export
Exporting is the process of making variables, functions, or components available for use in other files.
a. Named Export
export const myVariable = "Hello, World!";
export function myFunction() {
console.log("This is a function.");
}
b. Default Export
const myVariable = "Hello, World!";
export default myVariable;
2. Import
Importing allows you to bring in variables, functions, or components from another file into your current file.
a. Named Import
import { myVariable, myFunction } from './myModule';
console.log(myVariable); // "Hello, World!"
myFunction(); // "This is a function."
b. Default Import
import myVariable from './myModule';
console.log(myVariable); // "Hello, World!"
c. Importing Both Named and Default Exports
import myVariable, { myFunction } from './myModule';
console.log(myVariable); // "Hello, World!"
myFunction(); // "This is a function."
3. React Specific Import/Export Example
In React, components are usually exported and imported between different files.
a. Exporting a React Component
import React from 'react';
const MyComponent = () => {
return Hello, this is MyComponent!
;
};
export default MyComponent; // Default export
b. Importing a React Component
import React from 'react';
import MyComponent from './MyComponent'; // Default import
const App = () => {
return (
);
};
export default App;
c. Named Exports in React
import React from 'react';
export const MyComponentOne = () => {
return Component One
;
};
export const MyComponentTwo = () => {
return Component Two
;
};
import React from 'react';
import { MyComponentOne, MyComponentTwo } from './MyComponents'; // Named import
const App = () => {
return (
);
};
export default App;
Key Points:
- Default Export: You can export a single thing (function, object, or class) from a file. When importing, you can use any name.
- Named Export: You can export multiple things (functions, variables, components) from a file. When importing, you must use the exact name as the export.
- React Components: React components are commonly exported as default, but you can also use named exports for multiple components in a file.
Conclusion:
The import/export mechanism allows you to modularize your code in React. It helps in creating clean, maintainable code where different parts of your application can be reused and tested separately.