Ever wondered why we usually write 'export deafult [component name]' to export a React Component?
Ankita Sahu
Posted on October 11, 2021
It's been quite some time that I've been wondersing the exact reason behind using export deafult [component name] to export a react component,but recently I know why?
When we export a component with default ,it in return helps us to import that component with any name in the .js file we want to use it.Still confused? Check out this example
For a Greet component write down the following code:
import React from 'react'
function Greet() {
return (
<div>
<h1>Hello,Greetings!</h1>
</div>
)
}
export default Greet
In the App.js file
import './App.css';
import Greet from './Greet';
function App() {
return (
<div className="App">
<Greet />
</div>
);
}
export default App;
These two snippets generate the following output:
now if we change the import name in app.js and the snippet now looks similar to this:
import './App.css';
import Greetings from './Greet';
function App() {
return (
<div className="App">
<Greetings />
</div>
);
}
export default App;
Named Exports
Here the Greet.js would look similar to this:
import React from 'react'
export const Greet = () => <h1>Hello,Greetings</h1>
And the App.js similar to this:
import './App.css';
import {Greet} from './Greet';
function App() {
return (
<div className="App">
<Greet />
</div>
);
}
export default App;
In case of named components,we cannot change the name of the importing component on doing so it will generate an error,take a look at the App.js where we have changed the name in case of named components:
import './App.css';
import {Greetings} from './Greet';
function App() {
return (
<div className="App">
<Greetings />
</div>
);
}
export default App;
also take a look at the error generated:
Probably now you know export takes a default and what could happen if you use named components.
Posted on October 11, 2021
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.
Related
November 30, 2024