Page Content

Tutorials

What Are The Constructor in React.js With Code Example

Constructor in React.js

The constructor is a unique method in React.js that is used in class-based components. It is called at the beginning of the component’s building process, before any other lifecycle methods. Its main functions include binding event handler methods to the component instance and initialising the component’s local state by directly assigning an object to this.state, which is the only location where this.state should be explicitly assigned. Calling super(props) as the first statement in the constructor is essential when using ES6 classes (which extend React.Component); this calls the constructor of the parent React.Component and makes this.props available within the constructor of your component.

Because ES6 classes do not automatically bind this to methods like the deprecated React.createClass does, event handlers must either use arrow functions or manually bind this in the constructor. Functional components maintain state using Hooks like useState and lack constructors and conventional lifecycle methods, whereas class components use constructors for state and method binding.

Constructor in React.js
Constructor in React.js

Purpose of the Constructor

In a React class component, the constructor serves the following main functions:

Initializing State: This.state is the sole location where you may set up the initial state of a component by directly assigning an object to it. The private information of the component is represented by this state, which is subject to change and may necessitate re-renders.

Binding Event Handlers: JavaScript context difficulties may occur when declaring methods inside a class component that will be used as event handlers (for example, onClick events). In order to guarantee that the component instance is correctly referenced when the method is called, it is usual practice to bind these methods to it via the constructor.

The Role of Constructor

React class component constructors must start with super(props).

Calling Parent Constructor: The super() function calls React’s constructor for the parent class.part.

Accessing this.props: You can make sure that this.props is properly initialised and available within the constructor of your component by sending it as a parameter to super(). This.props would be undefined in the constructor without super(props), resulting in problems if you attempted to access it.

Initializing State

You specify the initial values and form of your component’s state in the constructor.

Direct Assignment: An object, such as this, can be directly assigned to this.state to set the initial state.{ key: ‘value’ }; state =? Only inside the constructor is this allowed; outside of it, you have to use this.To update the status, use setState().

Using Props for Initial State: The props that the component receives can be used to initialise state. This.state = { count: this.props.initialCount }; is an example.

Avoiding Anti-Patterns:If the state is just a duplicate of the prop and doesn’t change on its own, saving props directly into it is usually regarded as anti-pattern. This may result in discrepancies. Nonetheless, a prop is useful if its purpose is to initialise an internal state that can subsequently be changed by user interactions or other internal logic.

Replacement for getInitialState(): GetInitialState() was replaced by getInitialState(), which was used to set the default state in previous React applications created with React.createClass. Nevertheless, state is initialised directly within the constructor for ES6 class components, and getInitialState() is deprecated.

Binding Event Handlers

Working with class-based components requires binding event handlers in React.js, mainly because ES6 classes do not automatically tie this context to their methods like the earlier React.createClass did. As a result, access to the component’s props, state, and other similar methods will be blocked if an event handler method like a onClick or onChange function is performed without the appropriate binding. The this keyword inside that method will be null or undefined.setState().

Proper binding is necessary to enable dynamic user interfaces, regardless of the approach employed. For example, a onChange event handler must appropriately call this while handling form inputs.To reflect the user’s input in the DOM, a re-render is initiated once the component’s state is updated using setState(). Functional components, which were first introduced with React Hooks, do not require event handler binding in the same way as class components since they handle state and side effects differently (for example, by using useState and useEffect) and do not use this or the constructor for these reasons.

Code Example:

let’s demonstrate these ideas using a Product component that controls a basic shopping cart.

import React, { Component } from 'react';
class Product extends Component {
  state = {
    cart: [],
    total: 0,
    productName: this.props.initialProductName || 'Ice Cream',
    showInfo: false
  };
  addToCart = () => {
    this.setState(p => ({
      cart: [...p.cart, this.state.productName],
      total: p.total + 5
    }));
  };
  toggleInfo = () => {
    this.setState(p => ({ showInfo: !p.showInfo }));
  };
  render() {
    const { cart, total, productName, showInfo } = this.state;
    return (
      <div className="flex flex-col items-center p-6 bg-white rounded-3xl shadow-xl border">
        <h2 className="text-3xl font-extrabold mb-4">{productName} Shop</h2>
        <div className="text-lg mb-2">Cart: <span className="font-semibold">{cart.length}</span> items</div>
        <div className="text-lg mb-4">Total: <span className="font-bold">₹{total.toFixed(2)}</span></div>
        <div className="flex flex-col gap-4 w-full">
          <div className="flex justify-center text-5xl bg-blue-50 p-4 rounded-xl shadow-inner border"><span role="img" aria-label={productName}>🍦</span></div>
          <button onClick={this.addToCart} className="w-full px-6 py-3 bg-blue-600 text-white font-bold rounded-full shadow-lg hover:bg-blue-700 transition-transform hover:scale-105">Add to Cart</button>
          <button onClick={this.toggleInfo} className="w-full px-6 py-3 bg-gray-200 font-bold rounded-full shadow-md hover:bg-gray-300 transition-transform hover:scale-105">{showInfo ? 'Hide Info' : 'Show Info'}</button>
        </div>
        {showInfo && <p className="mt-6 p-4 text-center bg-yellow-50 rounded-lg border">This is a delicious {productName} made with fresh ingredients!</p>}
      </div>
    );
  }
}
export default function App() {
  return (
    <div className="flex items-center justify-center min-h-screen bg-gray-100 p-4 font-inter">
      <Product initialProductName="Mango Ice Cream" />
    </div>
  );
}

Output:

Mango Ice Cream Shop
Cart: 7 items
Total: ₹35.00
🍦
Add to Cart    Hide Info
This is a delicious Mango Ice Cream made with fresh ingredients!

Explanation of the Code Example

Import React, { Component } from ‘react’;: This line imports the Component class, which our Product class will extend, as well as the required React library.

Class Product extends Component { … }: Specifies the component of our React class. React components are code segments that define items and can be reused.

Constructor(props) { … }: When a Product instance is created, the constructor is invoked. It inherits its parent component’s props, or properties.

Super(props);: By ensuring that the React.Component constructor is called, this.props becomes accessible within our constructor and the component is initialised correctly.

This.state = { … };: The internal state of the component is initialised here. The default settings for the cart and total are used. ProductName is initialised with a prop if one is supplied; if not, ‘Ice Cream’ is used by default. This.state should be immediately assigned here and nowhere else.

This.addToCart = this.addToCart.bind(this);: The addToCart method is expressly bound to the component instance by this line. This guarantees that the this keyword inside addToCart correctly corresponds to the Product component, enabling it to access this when addToCart is invoked (for example, by the button’s onClick event).this.setState() and state. This.toggleInfo follows the same reasoning.

AddToCart() and toggleInfo() methods: The class defines these common JavaScript functions. They change component state with this.setState(), which redraws the component to reflect UI changes.

Render() method: The render() method returns the component’s user interface in JSX. The current state variables are retrieved using this.state.cart.length and total.

Conditional Rendering: This shows how JSX may conditionally render elements using JavaScript expressions.state.showInfo && (<p>…</p>) displays the paragraph only if showInfo is true.

The component’s state and event handlers are prepared for user activities in the constructor, creating a dynamic and responsive user interface.

Kowsalya
Kowsalya
Hi, I'm Kowsalya a B.Com graduate and currently working as an Author at Govindhtech Solutions. I'm deeply passionate about publishing the latest tech news and tutorials that bringing insightful updates to readers. I enjoy creating step-by-step guides and making complex topics easier to understand for everyone.
Index