React Class Component - Event

About

React - Event in the context of a What is a React Class Component?

Example

  • A Toggle component that renders a button that lets the user toggle between “ON” and “OFF” states:
class Toggle extends React.Component {

  constructor(props) {

    super(props);
    this.state = {isToggleOn: true};

    // This binding is necessary to make `this` work in the callback
    // In JavaScript, class methods are not bound by default. If you forget to bind this.handleClick and pass it to onClick, this will be undefined when the function is actually called.
    // This is not React-specific behavior; it is a part of how functions work in JavaScript. Generally, if you refer to a method without () after it, such as onClick={this.handleClick}, 
    // you should bind that method.
    this.handleClick = this.handleClick.bind(this);
    
  }

  // A common pattern is for an event handler to be a method on the class. 
  handleClick() {
    this.setState(prevState => ({
      isToggleOn: !prevState.isToggleOn
    }));
  }

  render() {
    // When using React you should generally not need to call ''addEventListener'' to add listeners to a DOM element after it is created. 
    // Instead, just provide a listener when the element is initially rendered.
    return (
      <button onClick={this.handleClick}>
        {this.state.isToggleOn ? 'ON' : 'OFF'}
      </button>
    );
  }
}

ReactDOM.render(
  <Toggle />,
  document.getElementById('root')
);
<div id="root">
<!-- called the "root" DOM node because everything inside it will be managed by React DOM -->
</div>





Discover More
React - Event

This page is DOM event handling in React. The React event e is a synthetic event defined according to the TR/DOM-Level-3-Events/W3C spec (no worry ...



Share this page:
Follow us:
Task Runner