Before React 16.8, Class components were the sole method for managing state and lifecycle in React, while Function components were deemed “stateless.” With the introduction of Hooks, Function components now offer nearly the same capabilities as Class components, making the need for Class components almost obsolete.
Despite the preference for Function components, Class components are not planned for removal from React. This section will provide an overview of using Class components in React.
Feel free to skip this section and use Function Components instead. |
Components are standalone and reusable code units that function like JavaScript functions but operate in isolation and return HTML through a render()
method. There are two types of components: Class components and Function components. This chapter will focus on Class components.
When creating a React component, its name must begin with an uppercase letter. The component must also include extends React.Component
to inherit from React.Component
, granting access to its functions. Additionally, the component needs a render()
method, which returns HTML.
Here’s an example of a Class component called Car:
class |
Now your React application includes a Car component that returns an <h2> element. To use this component, you can include it with the syntax <Car />, just like normal HTML.
Render the Car
component within the “root” element.
const |
If your component has a constructor() function, it will be called when the component is initialized. The constructor is where you set up the component’s properties, which in React should be stored in an object called state. You will learn more about state later in this tutorial.
Additionally, the constructor is where you must include the super() statement to honor the inheritance from the parent component, allowing your component to access all functions of React.Component.
Add a constructor function to the Car component and include a color property.
class |
Utilize the color property within the render() function.
class |
Another way to handle component properties is by using props. Props function like function arguments and are passed into the component as attributes. You will learn more about props in the next chapter.
Pass a color to the Car component using an attribute, and use this color in the render() function.
class |
If your component includes a constructor function, you should always pass the props to the constructor and also to React.Component using the super() method.
class |