1. Code
  2. JavaScript

Learn React 18: Writing Components as Classes

Scroll to top
60+ min read

We have written all our components as functions so far in this series. However, you can also use classes to create components in React. In fact, classes were preferred for creating complex components, and functions were limited to simple components.

In this lesson from our free full-length beginner course on React 18, you'll learn how to convert our function component from the last tutorial into a class component.

Creating a Class Component

We create a class component in React by extending React.Component as shown below. The class name is the same as the function name from the previous tutorial.

1
class RandomGenerator extends React.Component {
2
    // Other code for our class

3
}

Let's begin by adding a constructor to our class that will handle initialization.

1
class RandomGenerator extends React.Component {
2
  constructor(props) {
3
    super(props);
4
5
    this.state = {
6
      randomNumber: Math.floor(Math.random() * 1000) + props.low
7
    };
8
  }
9
}

We pass props to the constructor method where we call the Component superclass by using super(props). We also use the constructor to initialize the state of our component with the help of the state property. The state property is actually an object which we can use to store any type of information that we need. In our case, we use it to store our randomNumber.

We will now add a render() method to the class that will render our component. It will simply contain the JSX code we wrote for rendering the component.

1
render() {
2
    return (
3
      <div class="container">
4
        <h1>Random Number Generator</h1>

5
        <h2>{this.state.randomNumber}</h2>

6
      </div>

7
    );
8
}

You might have noticed that we replaced randomNumber with this.state.randomNumber. This is because the random number is stored inside the state property of our component class.

At this stage, our component will generate a random number and show it on screen just once. This makes sense because we haven't written any code to generate a new random number periodically.

Updating the Component State

Now, I would like to introduce you to the concept of mounting and unmounting in React. A component is considered to be mounted when it is first rendered to the DOM. A component is considered to be unmounted whenever the DOM produced by the component is removed from the webpage.

Mounting and unmounting are part of a component's lifecycle. There are special methods called componentDidMount() and componentWillUnmount() which run after a component is mounted and unmounted respectively.

The code inside componentDidMount() will run after the component has rendered to the DOM. We can set up a timer here that will update the state of our component every two seconds. Here is the code for the method:

1
componentDidMount() {
2
    this.numTimer = setInterval(() => {
3
      let tempVal = Math.floor(Math.random() * 1000) + this.props.low;
4
      this.setState({ randomNumber: tempVal });
5
    }, 2000);
6
}

Did you notice the call to this.setState() inside the arrow function? This call lets React know that the state of the component has changed and it needs to be rendered again. This will then trigger a call to the render() method. The render() method will see that the value of this.state.randomNumber has changed, and React will update the DOM to reflect the new value.

We store a reference to our timer in the numTimer field so that we can destroy it later when our component unmounts. The code for componentWillUnmount() should look like this:

1
componentWillUnmount() {
2
    clearInterval(this.numTimer);
3
}

Here is the complete code for our RandomGenerator component class to avoid any confusion.

1
class RandomGenerator extends React.Component {
2
  constructor(props) {
3
    super(props);
4
5
    this.state = {
6
      randomNumber: Math.floor(Math.random() * 1000) + props.low
7
    };
8
  }
9
10
  componentDidMount() {
11
    this.numTimer = setInterval(() => {
12
      let tempVal = Math.floor(Math.random() * 1000) + this.props.low;
13
      this.setState({ randomNumber: tempVal });
14
    }, 2000);
15
  }
16
17
  componentWillUnmount() {
18
    clearInterval(this.numTimer);
19
  }
20
21
  render() {
22
    return (
23
      <div class="container">
24
        <h1>Random Number Generator</h1>

25
        <h2>{this.state.randomNumber}</h2>

26
      </div>

27
    );
28
  }
29
}

The following CodePen demo shows our component class in action. Try to modify it so that the random number never goes above a specified limit.

Final Thoughts

We have now successfully implemented our random number generator as a class component. Using class components was the way to go when working with state in the past. However, things have changed with the introduction of hooks, and a lot of developers now prefer to use functional components. It is still a good idea to be comfortable with both approaches.

Did you find this post useful?
Want a weekly email summary?
Subscribe below and we’ll send you a weekly email summary of all new Code tutorials. Never miss out on learning about the next big thing.
Looking for something to help kick start your next project?
Envato Market has a range of items for sale to help get you started.