Why am I able to import a Bootstrap component in React with a different name?

Viewed 35

This is what I mean:

import BsssButtonGroup from "react-bootstrap/ButtonGroup";

This works the same way as:

import ButtonGroup from "react-bootstrap/ButtonGroup";

..and I don't understand why?

The BsssButtonGroup is not an existing or defined componend in the ButtonGroup component in React Bootstrap, so how am I able to import it? WHAT is being imported exactly? How does writing some random name work?? I thought you have to import the exported component? But BsssButtonGroup is not exported, so how am I able to import it then?

Also, what happens when I pass props to this component? Where are these props handled, and how can I access them?

1 Answers

In ECMA Script, there exist to kinds of exports in modules. default and named. In React, default exports are the rule, in Angular, e.g., named exports are preferred.

You can export an identifier (e.g. class) as a named export like this:

export class MyClass {}

You import it like this:

import { MyClass } from 'mymodule';

You can change the name of the imported identifier with this syntax:

import { MyClass as MyClassAlias } from 'mymodule';

In contrast, you can make an identifier the default export of a module like this:

class MyClass {}

export default MyClass;

A module can have at most one default export.

The import syntax is slightly different for the default export (you omit the curly braces):

import MyClass from 'mymodule';

Note that in that case MyClass is just a name you give the default export of mymodule when importing it. You could also have picked any other name and use that in the importing module. This allows you to refer to it in the module where you imported it using that name. This is why your code works just fine with the BsssButtonGroup import.

You can find more info on ECMAScript exports here.

Related