React components as ES6 classes

Creating react components that have state is easier with ES6 classes

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 like the other components with ReactDOM.render:

Get hands-on with 1200+ tech skills courses.