/* Code-Comments */

October 13, 2019

Exporting A Named Function As Default

Back in February I wrote a primer on exports and require. While the primer was helpful, one piece that never quite clicked, was how to export a React component as the default without splitting the export statement from the component definition.

The reason for that is that I typically define my components as function expressions, not function declarations.

For example:

const MyComponent = props => {
  /* ... */
export default MyComponent

There are some nice features of this approach, but I wanted to refactor to export in line.

This doesn’t work:

export default const MyComponent = (props) => {
  /* ... */

You’ll get an error: “Expression expected”

Nor does this:

export default MyComponent = props => {
  /* ... */

Here you’ll get “MyComponent is not defined.”

The answer is fairly straight forward - use a (named1) function declaration

export default function MyComponent(props) {
  /* ... */

Voilá. All very straight forward if I just spent


  • 1 Naming the function will make it easier for debugging purposes by assigning a name in the stack trace (as opposed to “anonymous”).

Stephen Weiss

Thanks for reading! My name's Stephen Weiss. I live in Chicago with my wife, Kate, and dog, Finn.
Click here to see the archives of my weeks in review and sign up yourself!