ScanSkill

constructor()

The constructor() method is the first method to be called in the lifecycle of a component. It is called to initialize a component and the state and props of a component are defined inside constructor() method. It is called with super(props) with props as an argument. This will initiate the parent's constructor method and allows the component to inherit methods from its parent component.

Syntax

class ClassName extends React.Component { 
    constructor(props) 
    { 
        super(props); 
          
        // initialize state
        this.state = { state : value}; 
    } 
} 

Example

class Example extends React.Component {
  constructor(props) {
    console.log("initialized");
    super(props);
    this.state = {name: "John Doe"};
  }
  render() {
    return (
      <h1>My name is {this.state.name}</h1>
    );
  }
}
constructor()