why I have to export const?

Viewed 144

I'm new to React and ES6, still struggling in understanding its syntax, below is an example code from my book:

import React from 'react';

export const App = () => <h1 className="bg-primary text-white text-center p-2">
  Hello Adam
</h1>

export default App;

but why I have to use 'const' as well, why I can't do like;

export default App = () => <h1 className="bg-primary text-white text-center p-2">
  Hello Adam
</h1>

it compiled but caused an runtime error,which I don't know why, I always can do the following without any errors:

export default function (…) { … } 

I'm really confused

3 Answers

There is no point in naming default export because when you are importing it, you can import it as anything

export default () => <h1 className="bg-primary text-white text-center p-2">
  Hello Adam
</h1>

// can be imported as
import Foo from './App';
import Bar from './App';
import AnythingYouCanThinkOf from './App';

If you want named import:

export const App = () => <h1 className="bg-primary text-white text-center p-2">
  Hello Adam
</h1>

// can be imported only as
import { App } from './App';

Also please note that there can be multiple named exports but only one default export in a single file.

export default () => <h1 className="bg-primary text-white text-center p-2">
  Hello Adam
</h1>
export const Header = () => <div>Header</div>
export const Footer = () => <div>Footer</div>
export const Sidebar = () => <div>Sidebar</div>

// imports
import AnyNameYouWantWhichIsDefaultExport, { Header, Footer, Sidebar } from './App'

You can just export default, but default exports do not enforce names on import. So, the code would look like this:

export default () => <h1 className="bg-primary text-white text-center p-2">
  Hello Adam
</h1>

When you are going to export a default value, you want to import it without name (name it exactly when you import it somewhere else) somewhere else then you can't just export default it with name so to export default you can do the following:

// Just export it
export default () => ...

// Or this way
const App = () => ...

export default App;
Related