ES6 Modules

React ES6 Modules (import and export)

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.


Exporting Modules

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.

1. Named 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.js

export const add = (a, b) => a + b; export const subtract = (a, b) => a - b;

// Alternatively, at the bottom of the file: // export { add, subtract };

2. Default Exports

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;


Importing Modules

How you import a module depends on whether it was exported as a named export or a default export.

1. Importing Named Exports

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

2. Importing Default Exports

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;


Mixing Default and Named Exports

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.

Importing File Paths

Notice the path used in the import statements: './Button.js'.


Summary


Exercise

?

If a component is exported using `export default Header;`, how must it be imported in another file?