React Class Component - Event

> (World Wide) Web - (W3|WWW) > Javascript (Js|ECMAScript) > React > Class Component

1 - About

React - Event in the context of a Class Component

3 - 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) {
    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'}
  <Toggle />,
<div id="root">
<!-- called the "root" DOM node because everything inside it will be managed by React DOM -->