Responding to Events

<!-- HTML Event Handler -->
<button onclick="handleData()">
  Submit Data
</button>
/* React Event Handler */
<button onClick={handleData}>
  Submit Data
</button>

Preventing Default Behavior

function Link () {
  function handleClick(event) {
    event.preventDefault();
    doSomethingWithTarget(event);
  }

  return (
    <a href="#" onClick={handleClick}>
      Click Me React
    </a>
  );
}

React Events are SyntheticEvents

Propery Return Type
bubbles boolean
cancelable boolean
currentTarget DOMEventTarget
defaultPrevented boolean
eventPhase number
isTrusted boolean
nativeEvent DOMEvent
preventDefault() void
isDefaultPrevented() boolean
stopPropagation() void
isPropagationStopped() boolean
target DOMEventTarget
timeStamp number
type string

Events are Nullified after Handling

Usual Behavior

function onClick(event) {
  console.log(event); // => nullified object.
  console.log(event.type); // => "click"
  const eventType = event.type; // => "click"

  setTimeout(function() {
    console.log(event.type); // => null
    console.log(eventType); // => "click"
  }, 0);

  // Won't work.
  // this.state.clickEvent will only contain null values.
  this.setState({clickEvent: event});

  // You can still export event properties.
  this.setState({eventType: event.type});
}

More on SyntheticEvents

Binding Event Handlers

class Toggle extends React.Component {
  constructor (props) {
    super(props);
    this.state = { isToggleOn: true };

    // Binding is necessary to make `this` work in the callback
    this.handleClick = this.handleClick.bind(this);
  }

  handleClick() {
    this.setState(prevState => ({
      isToggleOn: !prevState.isToggleOn
    }));
  }

  render() {
    return (
      <button onClick={this.handleClick}>
        {this.state.isToggleOn ? true : false}
      </button>
    );
  }
}

ReactDOM.render(
  <Toggle />,
  document.getElementById('root')
);

More about Binding Functions

Binding Event Handlers - Arrow Functions

class LoggingButton extends React.Component {
  // This syntax ensures `this` is bound within handleClick.
  // Warning: this is *experimental* syntax.
  constructor (props) {
    super(props)
    this.state = { isToggleOn: true }
  }

  handleClick = () => {
    this.setState(prevState => ({
      isToggleOn: !prevState.isToggleOn
    }));
  }

  render() {
    return (
      <button onClick={this.handleClick}>
        {this.state.isToggleOn ? true : false}
      </button>
    );
  }
}

Arrow Functions as Class Properties

 Previous Lesson Next Lesson 

Outline

[menu]

/