DEV Community

Petr Janik
Petr Janik

Posted on • Updated on

Export / Import components in React

Like with anything in programming, there are multiple ways to do the same thing.
In React app, we start with one main component, called App by default and compose it from other components. It is a good practice to have one component per file. When we want to use that component in another file, we have to export it from its file and import it in the file where we want to use it.

Therefore, I would like to address some ambiguity when using exports.

Named export

class TodoList extends React.Component {
  render() {
    return (
      <div>
        <h1>Todo list</h1>
      </div>
    );
  }
}
export { TodoList };
Enter fullscreen mode Exit fullscreen mode

This is equivalent to

export class TodoList extends React.Component {
  render() {
    return (
      <div>
        <h1>Todo list</h1>
      </div>
    );
  }
}
Enter fullscreen mode Exit fullscreen mode

Then, we can import it using

import { TodoList } from './TodoList';
Enter fullscreen mode Exit fullscreen mode

Default export

class TodoList extends React.Component {
  render() {
    return (
      <div>
        <h1>Todo list</h1>
      </div>
    );
  }
}

export default TodoList;
Enter fullscreen mode Exit fullscreen mode

Again, this is equivalent to

export default class TodoList extends React.Component {
  render() {
    return (
      <div>
        <h1>Todo list2</h1>
      </div>
    );
  }
}
Enter fullscreen mode Exit fullscreen mode

Then, we can import it using

import TodoList from './TodoList';
Enter fullscreen mode Exit fullscreen mode

or even

import MyList from './TodoList';
Enter fullscreen mode Exit fullscreen mode

The name by which we import it does not really matter at this point.

In React it's a convention to export one component from a file, and to export it as the default export.

Top comments (0)