In this article, we will learn how to use constractor in react js.
The function Object() { [native code] } is a method for initialising the state of an object in a class.
When an object in a class is created, it is automatically invoked.
In React, the concept of a function Object() { [native code] } is the same.
A React component’s function Object() { [native code] } is called before the component is mounted.
You must call super(props) function before any other statement when implementing the function Object() { [native code] } for a React component. This.props will be undefined in the function Object() { [native code] } if super(props) is not called, which might lead to errors.
Syntax
Constructor(props){ super(props); }
Constructors are mostly used in React for two purposes:
- It’s used to set the component’s local state by assigning an object to this.state.
- It is used to connect event handler functions in your component.
In the function Object() { [native code] }, you can’t use the setState() method ().
If the component requires local state, you must assign the initial state using ‘this.state’ explicitly in the function Object() { [native code] }.
This.state is only used in the function Object() { [native code] } to set the initial state; all other methods must use the set.state() function.
You can see below code how to use,
import React, { Component } from 'react'; class App extends Component { constructor(props){ super(props); this.state = { data: 'www.thecodehubs.com' } this.handleEvent = this.handleEvent.bind(this); } buttonHandler(){ console.log(this.props); } render() { return ( <div className="App"> <h2>React Constructor</h2> <input type ="text" value={this.state.data} /> <button onClick={this.buttonHandler}>Button</button> </div> ); } } export default App;