techStackGuru

React Events

react-events

In React, events allow users to interact with the page, such as clicking on a button or typing in an input field. There are some differences and conveniences with React's synthetic event system compared with native DOM events.

In React, there are some events that are commonly used:

onClick:

When a user clicks a DOM element, this event is fired.

<button onClick={handleClick}>Click me</button> 

onChange:

The event is triggered when the value of an input, select, or textarea element changes.

<input type="text" onChange={handleChange} /> 

onSubmit:

When the form is submitted, this method fires.

<form onSubmit={handleSubmit}>
{/* form fields */}
<button type="submit">Submit</button>
</form> 

onMouseOver and onMouseOut:

When the mouse pointer enters or leaves an element, this event is triggered.

<div onMouseOver={handleMouseOver} onMouseOut={handleMouseOut}>Hover over me</div> 

onKeyDown and onKeyUp:

It is triggered when the key is pressed down or released.

<input type="text" onKeyDown={handleKeyDown} onKeyUp={handleKeyUp} /> 

React's basic event handling can be summarized as follows.

Event Handling

import React, { useState } from 'react';

const EventHandlingExample = () => {
  const [count, setCount] = useState(0);

  const handleClick = () => {
    setCount(count + 1);
  };

  return (
    <div>
      <p>Count: {count}</p>
      <button onClick={handleClick}>Increment</button>
    </div>
  );
};

export default EventHandlingExample; 

HandleClick updates the count when a click is made. The handleClick function is called when the button is clicked, and it increments the count by one by using the setCount function. When the button element is clicked, the handleClick function is called via the onClick prop of the button element.


Event Binding

import React, { useState } from 'react';

const EventBindingExample = () => {
  const [message, setMessage] = useState('');

  const handleClick = () => {
    setMessage('Button clicked!');
  };

  return (
    <div>
      <p>{message}</p>
      <button onClick={handleClick}>Click Me</button>
    </div>
  );
};

export default EventBindingExample; 

Event binding is accomplished by assigning the event handler function (handleClick) directly to the button element's onClick prop. The handleClick function is invoked when the button is clicked.

Event Object

import React from 'react';

class Button extends React.Component {
  handleClick(event) {
    console.log('Button clicked!', event);
  }

  render() {
    return (
      <button onClick={this.handleClick}>Click Me</button>
    );
  }
}

export default Button; 

This example shows a React component called Button. Clicking the button calls the handleClick method. An event object representing the click event is passed as an event parameter to handleClick. In order to get more information about an event, you can access its various properties and methods, such as event.target.

Event Propagation

import React from 'react';

class ParentComponent extends React.Component {
  handleButtonClick = () => {
    console.log('Button clicked in ParentComponent');
  };

  render() {
    return (
      <div>
        <h1>Parent Component</h1>
        <ChildComponent onClick={this.handleButtonClick} />
      </div>
    );
  }
}

class ChildComponent extends React.Component {
  handleButtonClick = () => {
    console.log('Button clicked in ChildComponent');
    this.props.onClick(); // Call the onClick prop passed from the parent
  };

  render() {
    return (
      <div>
        <h2>Child Component</h2>
        <button onClick={this.handleButtonClick}>Click me</button>
      </div>
    );
  }
}

export default ParentComponent; 

A function handleButtonClick is passed to the child component as a prop called onClick by the ParentComponent. A message is logged to the console when the handleButtonClick function in the ChildComponent is called first. After that, the onClick prop is called, which executes the handleButtonClick function in the parent component. The parent component's handleButtonClick function is then invoked, logging another console message.

Event PreventDefault and StopPropagation

import React from 'react';

function MyComponent() {
  const handleLinkClick = (event) => {
    event.preventDefault();
    event.stopPropagation();
    console.log('Link clicked!');
  };

  const handleButtonClick = () => {
    console.log('Button clicked!');
  };

  return (
    <div>
      <a href="#" onClick={handleLinkClick}>
        Click me (Link)
      </a>
      <button onClick={handleButtonClick}>
        Click me (Button)
      </button>
    </div>
  );
}

export default MyComponent; 

As an onClick event handler, the handleLinkClick function is passed to the "a" element. The handleLinkClick function is called when the link is clicked. Event.preventDefault() is called to prevent default navigation to the specified URL (# in this case) from being performed. In addition, event.stopPropagation() is called in order to prevent the button's click event handler from being triggered.

By contrast, handleButtonClick is called as an onClick event handler on the button element. A "Button clicked!" message is logged to the console when the handleButtonClick function is executed.

This method controls events' default behavior and prevents them from propagating to other handlers by using preventDefault() and stopPropagation().