exporting a named function as default

2019-10-13

 | 

~1 min read

 | 

198 words

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

Footnotes

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

Hi there and thanks for reading! My name's Stephen. I live in Chicago with my wife, Kate, and dog, Finn. Want more? See about and get in touch!