React: Data Binding and Event

Level : Beginner
Mentor: Shailendra Chauhan
Duration : 00:01:00

Binding Event Handler in Render Method

This approach involves binding an event handler within the render method of a React component. While it works, it creates a new function instance on each render, potentially impacting performance.

Example

class RenderMethodBinding extends React.Component {
 handleClick() {
  // Handle click event
 }
 render() {
  return <button onClick={this.handleClick.bind(this)}>Click Me</button>;
 }
}

Binding Event Handler using Arrow Function

Using an arrow function to define the event handler inside the JSX directly avoids the need for manual binding and provides a more concise syntax.

Example

class ArrowFunctionBinding extends React.Component {
 handleClick = () => {
  // Handle click event
 };
 render() {
  return <button onClick={this.handleClick}>Click Me</button>;
 }
}

Binding Event Handler in the Constructor

Binding the event handler in the component's constructor is a common pattern, ensuring the binding occurs only once.

Example

class ConstructorBinding extends React.Component {
 constructor() {
  super();
  this.handleClick = this.handleClick.bind(this);
 }
 handleClick() {
  // Handle click event
 }
 render() {
  return <button onClick={this.handleClick}>Click Me</button>;
 }
}

Binding Event Handler using Arrow Function as a Class Property

This is a modern approach using class properties, where arrow functions automatically bind to the instance.

Example

class ArrowFunctionPropertyBinding extends React.Component {
 handleClick = () => {
  // Handle click event
 };
 render() {
  return <button onClick={this.handleClick}>Click Me</button>;
 }
}
Self-paced Membership
  • 24+ Video Courses
  • 825+ Hands-On Labs
  • 400+ Quick Notes
  • 125+ Skill Tests
  • 10+ Interview Q&A Courses
  • 10+ Real-world Projects
  • Career Coaching Sessions
  • Email Support
Upto 60% OFF
Know More
Still have some questions? Let's discuss.
CONTACT US
Accept cookies & close this