Ever wondered why we usually write 'export deafult [component name]' to export a React Component?

sahu01

Ankita Sahu

Posted on October 11, 2021

Ever wondered why we usually write 'export deafult [component name]' to export a React Component?

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
Enter fullscreen mode Exit fullscreen mode

In the App.js file

import './App.css';
import Greet from './Greet';

function App() {
  return (
    <div className="App">
      <Greet />
    </div>
  );
}

export default App;
Enter fullscreen mode Exit fullscreen mode

These two snippets generate the following output:
image

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;

Enter fullscreen mode Exit fullscreen mode

The result is the same:
image

Named Exports

Here the Greet.js would look similar to this:

import React from 'react'

export const Greet = () => <h1>Hello,Greetings</h1>
Enter fullscreen mode Exit fullscreen mode

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;
Enter fullscreen mode Exit fullscreen mode

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;
Enter fullscreen mode Exit fullscreen mode

also take a look at the error generated:
image

Probably now you know export takes a default and what could happen if you use named components.

πŸ’– πŸ’ͺ πŸ™… 🚩
sahu01
Ankita Sahu

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