Constructor
Constructor in React Components
In general, the constructor method in a class is used to initialize a newly created object. React also uses the constructor() method for initialization, but with additional responsibilities.
In class-based React components, the constructor is mainly used for:
Initializing props
Initializing state
Binding event handlers
Let us understand each of these step by step
Initializing Props
Every React component can receive props and manage state. In class components, props must be initialized using the super(props) call inside the constructor. If this is not done, this.props will not work correctly and may cause bugs.
Example: Initializing Props
class Welcome extends React.Component { constructor(props) { super(props); } render() { return (
Welcome {this.props.name}
Explanation
super(props) initializes the props
this.props.name gives access to the name prop
Using the Component
function App() { return (
Output
Welcome John
Initializing State
Just like props, state initialization is also done inside the constructor. State represents data that can change over time.
Common Ways to Work with State
1. Initialize State
this.state = { pageSize: 10 };
2. Access State
this.state.pageSize
3. Update State
this.setState({ pageSize: 20 });
Or using a callback function:
this.setState((state, props) => ({ pageSize: state.pageSize + 1 }));
Example: Component with State Initialization
class Welcome extends React.Component { constructor(props) { super(props); this.state = { welcomeMessage: "Hello" }; } render() { return (
{this.state.welcomeMessage}, {this.props.name}
Using the Component
function App() { return (
Output
Hello, John
Event Binding in Constructor
In class-based components, event handlers must be bound to the component instance. Without binding, the this keyword inside the handler will be undefined.
Example: Event Binding
import React from "react"; class Welcome extends React.Component { constructor(props) { super(props); this.state = { welcomeMessage: "Hello" }; this.changeMessageHandler = this.changeMessageHandler.bind(this); } changeMessageHandler() { this.setState(prevState => ({ welcomeMessage: prevState.welcomeMessage === "Hello" ? "Welcome" : "Hello" })); } render() { return (
{this.state.welcomeMessage}, {this.props.name}
Steps Explained
Button with event
Bind handler in constructor
this.changeMessageHandler = this.changeMessageHandler.bind(this);
Update state using setState()
this.setState(prevState => ({ welcomeMessage: prevState.welcomeMessage === "Hello" ? "Welcome" : "Hello" }));
Using the Component
function App() { return (
Output
Initially: Hello, John
After clicking button: Welcome, John