Search⌘ K

React components as ES6 classes

Explore creating stateful React components using ES6 class syntax. Learn how to initialize state, render dynamic content, and update state with event handlers to build interactive UI elements like counters. This lesson helps you understand class-based components and event binding in React.

We'll cover the following...

Classes

As mentioned in the “Why React?” section, React has the virtual DOM to minimize rerendering when the application state changes. But what is application state and how do we manage it in React?

Any real world application will have state. State can be anything and everything, ranging from “this checkbox is checked” over “that modal is open” to “this data was fetched”.

As a simple example of state, let’s create a Counter component that counts how often we’ve clicked a button! Our Wrapper component above was written as a functional component. To create stateful components, we have to use a slightly different notation to create components – the class notation!

To create a stateful component, we create a new class that extends React.Component. (React.Component is a base we can build upon that React provides for us) We assign it a render method from which we return our ReactElements, not unlike the functional component:

class Counter extends React.Component {
  render() {
    return (
      <p>This is the Counter component!</p>
    );
  }
}

We can then render this component just ...