Open In App

React.js constructor() Method

A constructor is a method that is called automatically when we created an object from that class. It can manage initial initialization tasks such as defaulting certain object properties or sanity testing the arguments passed in. Simply placed, the constructor is a method that helps in the creation of objects. 

The constructor is no different in React. This can connect event handlers to the component and/or initialize the component’s local state. Before the component is mounted, the constructor() function is shot, and, like most things in React, it has a few rules that you can follow when using them.



Creating React Application:

Project Structure: It will look like the following.

Example: Now write down the following code in the App.js file. Here, App is our default component where we have written our code. The following example covers constructor demonstration.




import React, { Component } from 'react';
  
class App extends Component {
  
  constructor(props) {
  
    // Calling super class constructor
    super(props);
      
    // Creating state
    this.state = {
      data: 'My name is User'
    }
      
    // Binding event handler
    this.handleEvent = this.handleEvent.bind(this);
  }
  
  handleEvent() {
    console.log(this.props);
  }
  
  render() {
    return (
      <div >
        <input type="text" value={this.state.data} />
        <br></br> <br></br>
        <button onClick={this.handleEvent}>Please Click</button>
      </div>
    );
  }
}
  
export default App;

Step to Run Application: Run the application  from the root directory of the project, using the following command

npm start

Output:


Article Tags :