loading...

Export / Import components in React

petr7555 profile image Petr Janik ・1 min read

React (3 Part Series)

1) Export / Import components in React 2) Classes vs Functional components in React 3) Beginner's guide to React State

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};

This is equivalent to

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

Then, we can import it using

import {TodoList} from "./TodoList";

Default export

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

export default TodoList;

Again, this is equivalent to

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

Then, we can import it using

import TodoList from "./TodoList";

or even

import MyList from "./TodoList";

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.

React (3 Part Series)

1) Export / Import components in React 2) Classes vs Functional components in React 3) Beginner's guide to React State

Posted on Jun 3 by:

petr7555 profile

Petr Janik

@petr7555

I'm a student of applied informatics at Masaryk University in Brno. I love coding, especially in Java and Python.

Discussion

markdown guide