As your React applications grow, keeping all your code in a single file becomes impossible to manage. ES6 introduced Modules, allowing you to split your JavaScript code into smaller, reusable files.
In React, every file is treated as a module. You create a component in one file, export it, and then import it into another file where it's needed.
You can export functions, objects, variables, or entire React classes. For example, here is a React class component:
import React from 'react';class Welcome extends React.Component { render() { return <h1>Hello, Class Component!</h1>; } }
There are two different types of exports: Named Exports and Default Exports.
Named exports allow you to export multiple things from a single file. You can either place the export keyword in front of the declaration, or export them all together at the bottom.
// File: math.jsexport const add = (a, b) => a + b; export const subtract = (a, b) => a - b;
// Alternatively, at the bottom of the file: // export { add, subtract };
You can only have one default export per file. In React, it is a standard convention to use a default export for the main Component inside a file.
// File: Button.js import React from 'react';const Button = () => { return <button>Click Me</button>; };
// Exporting as default export default Button;
How you import a module depends on whether it was exported as a named export or a default export.
To import named exports, you must use curly braces {} and the names must match exactly what was exported.
// File: App.js import { add, subtract } from './math.js';console.log(add(5, 5)); // 10
To import a default export, you do not use curly braces. Furthermore, because it's the default export, you can technically name it whatever you want when you import it (though keeping the name consistent is highly recommended).
// File: App.js// Importing the default export Button from Button.js import Button from './Button.js';
const App = () => { return ( <div> <h1>Welcome to my App</h1> <Button /> </div> ); };
export default App;
A single file can contain both one default export and multiple named exports.
You've likely seen this in React when importing Hooks:
// React library exports 'React' as default, and 'useState' as a named export import React, { useState } from 'react';
This works seamlessly and is a very common pattern in large library ecosystems.
Notice the path used in the import statements: './Button.js'.
./ for the same folder, ../ for one folder up).'react'), you just use the library's name without any path structure.export const myVar = 1) allow multiple exports per file and must be imported with curly braces {}.export default MyComponent) allow only one export per file and are imported without curly braces.export default syntax.If a component is exported using `export default Header;`, how must it be imported in another file?