devmeetings-react-ts-fork
  • Devmeeting React + Typescript
  • Speed dating
  • Typescript
    • It's just JavaScript
    • Basic types
    • Typing objects
    • Typing functions
    • Modules
    • Generics
    • Tasks
  • Hello React
    • Quick look around
    • The first component
    • JSX
    • Tasks
  • Components & Props
    • Small components
    • Passing data to a component
    • Loops in JSX
    • Tasks
  • Stateful components
    • Handling events
    • Components with internal state
    • Talking to a parent component
    • Smart and dumb components
    • Before the break
    • Tasks
  • Side-effects and context
    • Side-effects
    • Prop drilling
    • Using context
    • Tasks
  • What's next
    • Styling
    • Learning component's lifecycle
    • State Management
Powered by GitBook
On this page
  • Pass, not call
  • Fake event
  • Resources

Was this helpful?

  1. Stateful components

Handling events

PreviousStateful componentsNextComponents with internal state

Last updated 5 years ago

Was this helpful?

Let's build a simple button that does nothing besides logging to console:

import React, {MouseEvent} from 'react'

const Clicker: React.FC = () => {
    const handleButtonClick = (event: MouseEvent<HTMLElement>) => {
        console.log(event.currentTarget.textContent)
    }

    return (
        <button onClick={handleButtonClick}>Click me!</button>
    )
}

In React, all event listeners are attached to an element via onEventName property. This is similar to veeery old school JavaScript, but uses camelCase.

Pass, not call

It's important to remember that we are passing the callback as a prop, not calling it:

<button onClick={handleButtonClick()}>Click me!</button>

As long as we don't intent to call this function each time a component is rerendered.

Fake event

Resources

The event received in the callback is slightly different than expected. For starters, it's imported from React instead of just being in global namespace. In fact, it's an instance of the - this is quite important for React internals, but for us it's just there to avoid a gotcha moment.

Synthetic Event
List of supported events
Handling Events
clicker