Reputation: 3603
I'm new to nodejs + react and I guess this is a basic react syntax. I'm just not used to it coming from another language. I want to confirm if I'm right:
I am trying an open react project which is successfully deployed and works for sure.
In the entry file, index.js
:
...some code...
import AdminLayout from "layouts/Admin/Admin.js";
...some code...
ReactDOM.render(
<ThemeContextWrapper>
<BackgroundColorWrapper>
<BrowserRouter>
<Switch>
<Route path="/admin" render={(props) => <AdminLayout {...props} />} />
<Route path="/rtl" render={(props) => <RTLLayout {...props} />} />
<Redirect from="/" to="/admin/dashboard" />
</Switch>
</BrowserRouter>
</BackgroundColorWrapper>
</ThemeContextWrapper>,
document.getElementById("root")
For the component AdminLayout
, it is imported from layouts/Admin/Admin.js
. However, I checked the file and there is no variable named AdminLayout
at all, layouts/Admin/Admin.js
is as follows:
...some code...
function Admin(props) {
...some code...
}
export default Admin;
There is just the Admin
being exported.
So, is it true that in react, you can import a component with a different name?
I did some search but cannot any description on this small detail.
Upvotes: 6
Views: 12079
Reputation: 2412
This is actually not related to React but rather to Javascript modules.
Since the Admin component is exported as a default export:
export default Admin;
you can indeed importing it using any name.
The line: import AdminLayout from "layouts/Admin/Admin.js";
is a shorhand for import {default as AdminLayout} from "layouts/Admin/Admin.js";
where you can see more precisely what's happening there: you're importing the default exported module from Admin.js
and naming it to AdminLayout.
You could as well have used a named export in your Admin.js
file:
export function Admin(props) {
...some code...
}
or:
function Admin(props) {
...some code...
}
export {Admin}
In that case you must import the module using its name (and that obviously will also be the name of your React component):
import { Admin } from "layouts/Admin/Admin.js";
// In your render function you'll have at some point:
// ... <Route path="/admin" render={(props) => <Admin {...props} />} />
But note that you can as well rename an imported named export:
import { Admin as AdminLayout } from "layouts/Admin/Admin.js";
// In your render function you'll have at some point:
// ... <Route path="/admin" render={(props) => <AdminLayout {...props} />} />
It is also worth noting that while you can have multiple named exports per module:
export function Foo(){};
export const bar;
you can only have a single default export.
Upvotes: 5