Using import aliases when importing Components in React

avatar

Borislav Hadzhiev

Sat Apr 23 20222 min read

Using import aliases when importing Components in React #

To use import aliases when importing components in React, use the as keyword to rename the imported component, e.g. import {Button as MyButton} from './another-file'. The as keyword allows us to change the identifying name of the import.

Here is an example of a file called App.js which imports a component named Button.

App.js
// 👇️ rename import to MyButton import {Button as MyButton} from './another-file'; export default function App() { return ( <div> <MyButton /> </div> ); }

Here are the contents of another-file.js.

another-file.js
export function Button() { return <button onClick={() => console.log('button clicked')}>Click</button>; }

The path of the import in the App.js file assumes that another-file.js is located in the same directory.

For example, if importing from one directory up, you would have to import from '../another-file'.

You can use the as keyword to rename your imports and exports.

For example, we could export the component using a different name.

another-file.js
function Button() { return <button onClick={() => console.log('button clicked')}>Click</button>; } // 👇️ export as MyButton export {Button as MyButton};

We renamed the export of the Button component to MyButton, so now you would import it as:

App.js
import {MyButton} from './another-file'; export default function App() { return ( <div> <MyButton /> </div> ); }

The as keyword can be used to rename both imports and exports.

If your component is exported using a default export, you don't have to use the as keyword, because you are able to directly rename a default export when importing.

another-file.js
function Button() { return <button onClick={() => console.log('button clicked')}>Click</button>; } // 👇️ Uses default export export default Button;

Now, we can import the Button component as MyButton without using the as keyword.

App.js
// 👇️ can directly rename when importing (because default export) import MyButton from './another-file'; export default function App() { return ( <div> <MyButton /> </div> ); }

The main difference between named and default exports and imports is - you can have multiple named exports per file, but you can only have a single default export.

If you try to use multiple default exports (for functions, classes, variables) in a single file, you would get an error.

In my experience, most real world codebases exclusively use named exports and imports, because they make it easier to leverage your IDE for autocompletion and auto-imports.

Use the search field on my Home Page to filter through my more than 1,000 articles.