How to Handle Events in React
Responding to clicks, typing and form submits in React components.
When building React components you'll need to respond to things the user does, like clicking a button, typing in an input or submitting a form. React handles events with props that look a lot like the HTML attributes you already know, with a couple of small differences.
Handling a Click
Pass a function to the onClick prop:
import React from "react"function SaveButton() {const handleClick = () => {console.log("Saved!")}return <button onClick={handleClick}>Save</button>}
There are two differences from HTML. Event names are camelCase (onClick, not
onclick), and you pass a function instead of a string.
Important! Pass the function, don't call it. onClick={handleClick()} runs
the function on every render instead of on click.
Passing Arguments
When the handler needs to know which item was clicked, wrap it in an arrow function:
const TodoList = ({ todos, onDelete }) => (<ul>{todos.map((todo) => (<li key={todo.id}>{todo.title}<button onClick={() => onDelete(todo.id)}>Delete</button></li>))}</ul>)
The arrow function only runs when the button is clicked, and then it calls
onDelete with the right id. If the map and key here look new, check out
How to Render a List in React.
The Event Object
React passes an event object to every handler. For inputs, the value is on
e.target.value. Here it's saved with useState, which gives the component a
value to remember and a function to update it:
import React, { useState } from "react"function NameInput() {const [name, setName] = useState("")const handleChange = (e) => {setName(e.target.value)}return (<div><input value={name} onChange={handleChange} /><p>Hello, {name}</p></div>)}
In React, onChange fires on every keystroke, not only when the input loses
focus like the plain HTML change event.
Preventing the Default
Submitting a form reloads the page by default. In React, returning false from
a handler won't stop that. Call e.preventDefault() instead:
function SignupForm() {const [email, setEmail] = useState("")const handleSubmit = (e) => {e.preventDefault()console.log("Signing up", email)}return (<form onSubmit={handleSubmit}><inputtype="email"value={email}onChange={(e) => setEmail(e.target.value)}/><button type="submit">Sign up</button></form>)}
Putting onSubmit on the form instead of onClick on the button means pressing
Enter in the input submits it too.
Have some feedback on this post? .