Facebook PixelReact Class | React JS Tutorial | CodeWithHarry

React Class

Class Based Components

Before making a class-based component, we need to inherit functions from React.Component, and this can be done with extends, like this:

class Cat extends React.Component {
  render() {
    return <h1>Meow</h1>;
  }
}

It also requires a render method which returns HTML.

Note: Component's name must start with an uppercase letter.

Component Constructor

The constructor gets called when the component is initiated. This is where you initiate the component's properties. In React, we have states which update on the page without reload. Constructor properties are kept in state.

We also need to add the super() statement, which executes the parent component's constructor, and the component gets access to all the functions of the parent component, like this:

class Cat extends React.Component {
  constructor() {
    super();
    this.state = { color: "orange" };
  }
  render() {
    return <h1>Meow's color is {this.state.color}</h1>;
  }
}