Last updated: Apr 6, 2024
Reading timeยท2 min
To use import aliases when importing components in React, use the as
keyword
to rename the imported component.
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
.
// ๐๏ธ 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
.
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.
'../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.
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:
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.
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.
// ๐๏ธ 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 that 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 auto-completion and auto-imports.
You can learn more about the related topics by checking out the following tutorials: