A React component describes a part of the UI. Its purpose is to return HTML to a web page.
There are two ways to create React components: function components and class components. Nowadays, we use function components because they are simpler and easier to read.
A function component is a JavaScript function that returns a React element (can use JSX).
The component name (i.e., function name) must have an uppercase first letter. It is a convention to differentiate components from regular functions. Components are named with PascalCase, while regular functions are named with camelCase.
By convention, the component name should be the same as the file name. For example, the component in App.js
should be named App
. You can also use the jsx
extension (e.g., App.jsx
). If you use TypeScript, you can use the ts
or tsx
extension (e.g., App.tsx
). It is common in some frameworks to use kebab-case for file names (e.g., app-component.js
).
It is a good practice to store each component in a separate file. The function component must be the default export of the file.
The function must return a “React element.” Notice the syntax that looks like HTML. This is called JSX (JavaScript XML). We will explore JSX in more detail in a later note.
By convention, the argument is named props
. It is an object that contains all the properties passed to the component. It can be omitted if “props” are not used. We will explore props in more detail in a later note.
You can define function components using the arrow function syntax:
Function components used to be called “state-less components.” However, with the introduction of “Hooks” (since React 18), function components can hold “state.”
A class component is a JavaScript class that extends the Component
class from the react
library. It must have a render
method that returns a React element (can use JSX).
A class component must extend the Component
class from react
library.
A class component must have a render
method that a React element (can use JSX).
A class component should have a constructor that receives a props
argument and passes it to the parent constructor (using the super
keyword). If the constructor has no other purpose, it can be omitted.
All the conventions for function components apply to class components. The component name must have an uppercase first letter, and it should be the same as the file name. The component must be the default export of the file.
Class components are also called state-full components. The component’s “state” must be stored in an object called state
. This object must be a class property. It can be declared inside the constructor or as a field.
As of React 18, class components are considered legacy and are not recommended for new projects. Use function components instead.