← react hacks / react / adding-event-handlers-in-jsx.md

Adding Event Handlers in JSX

Learn how to add event handlers in JSX. A step-by-step guide to understanding and implementing event handlers in React's JSX syntax.

To add event handlers in JSX, we utilize camelCase syntax rather than lowercase. Let’s consider a button click event. In plain JavaScript, it would look like this:

<button onclick="activateFunction()">Click Me!</button>

In React’s JSX, we modify it to:

<button onClick={activateFunction}>Click Me!</button>

Here activateFunction is a function defined in your component. Remember, in JSX, you pass a function as the event handler, rather than a string.

Event handlers in React are attached directly to components and, when using class components, typically trigger methods. This is slightly different from assigning events to DOM in HTML.

class MyComponent extends React.Component {
  activateFunction() {
    // your code here
  }

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

Note: Make sure to bind your methods in class components to access this.

This guide should help you get started with event handlers in JSX!

Keep experimenting!

Quick hacks and tips from my daily workflow. Found this useful? Let me know.

@samuellawrentz →

$ ls ../react | head -4

More hacks

cd ../react →
  1. 3450e43 Enhancing Your Coding Experience with Neovim: A Beginner’s Guide

    tag: neovimtag: codingtag: productivity

  2. 9676c32 Understanding Neovim: How to Customize and Improve Your Text Editor

    tag: neovimtag: text-editortag: customization

  3. c52b973 Harnessing the Power of useRef Hook in React

    tag: reacttag: hookstag: useRef

  4. 2c098c3 Avoiding Unnecessary Re-renders with React.memo

    tag: reacttag: web developmenttag: performance optimization

00:00

This helps me increase the session time of my site. Thank you!

Can you stay a bit longer?