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.
Top comments (0)