← React Beginner Questions - Set 2 Q15

How does React handle events?

React Beginner Questions - Set 2

React handlers look like inline HTML but are real functions, and the event object is a wrapper with the same shape across browsers.

Example

import { useState } from 'react';

export default function SearchBox() {
  const [query, setQuery] = useState('');

  function handleSubmit(event) {
    event.preventDefault();         // stop the full page reload
    console.log('searching', query);
  }

  return (
    <form onSubmit={handleSubmit}>
      <input
        value={query}
        onChange={e => setQuery(e.target.value)}
        onKeyDown={e => e.key === 'Escape' && setQuery('')}
      />
      <button type="submit">Search</button>
      <button type="button" onClick={() => setQuery('')}>Clear</button>
    </form>
  );
}

What to notice

← Back to the question list