How to import / export in React/ES6?

Quick note that might help some of you.

How to import / export classes (especially components) in React/ES6?

The errors

If you get distracted you might end up exporting or importing your classes the wrong way. And getting one of these errors:

Uncaught Invariant Violation: Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: undefined. Check the render method of `YourComponent`.

or

Uncaught TypeError: Super expression must either be null or a function, not undefined

One possibility: default

If you have a closer look at your class YourComponent, you probably defined it like this:

export class YourComponent extends React.Component

And then tried to import it in another file like this:

import YourComponent from './YourComponent'

For this particular case, YourComponent should be declared as default, like this:

export default class YourComponent extends React.Component

And then your import will work.

Other possibility: no default

Now let’s say your module YourComponent.js contains more than one class/var and you don’t really want to default any of them.

You will keep declaring YourComponent like this:

export class YourComponent extends React.Component

And change your import to use curly braces, like this:

import { YourComponent } from './YourComponent'

N.B.: The Airbnb styleguide disallows having multiple class components in the same file. But you can use stateless components.

More examples

You will find more examples at these addresses: