In React, we can either use classes or functions for our components.
Classes
As you may have noticed in the first part of this series, we can create a React component as a class. To do so, we have to extend a React.Component
class and implement its render()
method.
This method must return either one root element or a fragment.
- This class renders a
<div>
and its contents.
export default class TodoList extends React.Component {
render() {
return (
<div>
<h1>Todo list</h1>
</div>
);
}
}
- This class renders a fragment.
export default class TodoList extends React.Component {
render() {
return (
<>
<h1>Todo list</h1>
<h1>Second element</h1>
</>
);
}
}
Alternatively
export default class TodoList extends React.Component {
render() {
return (
<React.Fragment>
<h1>Todo list</h1>
<h1>Second element</h1>
</React.Fragment>
);
}
}
Using fragments enables us to have multiple elements on the same level without having any <div>
around them.
Functions
Instead of classes, we can write our components as functions.
The rules for the export and import are the same as with classes.
The function itself must return either one root element or a fragment.
Default export
- Named function
export default function TodoList() {
return (
<div>
<h1>Todo list</h1>
</div>
);
}
- Anonymous function
When using default export, we may omit the name completely.
However, I do not recommend this.
export default function () {
return (
<div>
<h1>Todo list</h1>
</div>
);
}
- Named arrow function
const TodoList = () => {
return (
<div>
<h1>Todo list</h1>
</div>
);
};
export default TodoList;
- Anonymous arrow function
export default () => {
return (
<div>
<h1>Todo list</h1>
</div>
);
};
Named export
- Named function
export function TodoList() {
return (
<div>
<h1>Todo list</h1>
</div>
);
}
- Named arrow function
export const TodoList = () => {
return (
<div>
<h1>Todo list</h1>
</div>
);
};
Another not so fashionable option could be
export const TodoList = function () {
return (
<div>
<h1>Todo list</h1>
</div>
);
};
Personally, I prefer writing the React components as arrow functions.
Latest comments (2)
You could just
export default
anonymous arrow functionThank you, I have corrected it.