Class components should be the exception rather than the norm in your React applications. Still, let's explore these a bit to see how they are written.
To create a class component, you need to extend the React.Component class and implement the render method. That method will be the one creating/returning a React element.
Here is an example of a component class using ES2015 (that is, not TypeScript yet!):
const createElement = React.createElement; class SayHiButton extends React.Component { constructor(props) { super(props); this.state = { buttonClicked: false, }; } render() { console.log('Rendering'); if (this.state.buttonClicked) { console.log('The buttonClicked property of the state is
true; showing the message'); return 'Hello from React!'; } return createElement( 'button', { onClick: () => { console.log("The button's click handler was
clicked. Changing the state of the component"); this.setState({ buttonClicked: true, }, null) } }, 'Say hi!' // button's text ); } } const domContainer = document.querySelector('#hello-react-container'); ReactDOM.render(createElement(SayHiButton), domContainer);
In this example, we created a SayHiButton component, which simply displays a different message based on its internal state. Don't worry about the state management logic; we'll come back to that a bit later.
Class components, like function components, receive their inputs as a single props object. In the case of class components, those properties are passed to the constructor function.
In the constructor function of this example, we passed the props object to the parent class, then we initialized the state object of the component (more on this later).
In the render method, we used the React.createElement(...) function to create and return a React element.
Finally, notice that, in this example, we reused the standard button HTML element. Also, we used the second parameter of createElement to define an event handler.
Here's another example, this time using JSX:
export class Foo extends React.Component { constructor(props) { super(props); } render() { return ( <div>Bar</div> ); } }
From these two examples, what we mentioned earlier should become much more obvious: using the class-based approach for defining components is quite verbose.
As time passes and as React evolves, class components become less and less appealing. In the most recent releases, Functional Components have grown to be a lot more powerful than before. Let's take a look at those now.
Let's look at function components next.