SyntaxStudy
Sign Up
React Keyboard, Focus, and Other Event Types
React Beginner 1 min read

Keyboard, Focus, and Other Event Types

React supports the full spectrum of DOM events through synthetic event handlers. Beyond `onClick` and `onChange`, commonly used events include `onKeyDown`/`onKeyUp`/`onKeyPress` for keyboard interaction, `onFocus`/`onBlur` for focus management, `onMouseEnter`/`onMouseLeave` for hover effects, `onScroll` for scroll position, and `onDragStart`/`onDrop` for drag-and-drop. All follow the camelCase convention and receive a SyntheticEvent as their argument. Keyboard events provide the `key` property (e.g. `"Enter"`, `"Escape"`, `"ArrowUp"`) and modifier flags (`shiftKey`, `ctrlKey`, `altKey`, `metaKey`). Checking `e.key === "Enter"` is preferred over `e.keyCode` because `keyCode` is deprecated. A common pattern is to submit a chat message when the user presses Enter but inserts a newline when Shift+Enter is pressed. Focus events are essential for accessibility and custom UI patterns like closing a dropdown when it loses focus. `onFocus` fires when an element receives focus; `onBlur` fires when it loses focus. Note that React's `onFocus` and `onBlur` bubble (unlike their native equivalents), so you can attach them to a container and handle focus events for all children from one handler. This is useful for implementing the "focus within" behaviour needed for dropdown and tooltip components.
Example
import { useState, useRef } from 'react';

// Search box: submit on Enter, clear on Escape
function SearchBox({ onSearch }) {
  const [query, setQuery] = useState('');
  const inputRef = useRef(null);

  const handleKeyDown = (e) => {
    if (e.key === 'Enter' && query.trim()) {
      onSearch(query.trim());
    }
    if (e.key === 'Escape') {
      setQuery('');
      inputRef.current.blur();
    }
  };

  return (
    <input
      ref={inputRef}
      type="search"
      value={query}
      placeholder="Search… (Enter to submit, Esc to clear)"
      onChange={e => setQuery(e.target.value)}
      onKeyDown={handleKeyDown}
    />
  );
}

// Hover card using onMouseEnter / onMouseLeave
function HoverCard({ label, detail }) {
  const [visible, setVisible] = useState(false);
  return (
    <span
      style={{ position: 'relative', display: 'inline-block', cursor: 'pointer' }}
      onMouseEnter={() => setVisible(true)}
      onMouseLeave={() => setVisible(false)}
    >
      {label}
      {visible && (
        <span style={{ position: 'absolute', top: '1.5em', left: 0, background: '#333', color: '#fff', padding: '4px 8px', borderRadius: 4, whiteSpace: 'nowrap' }}>
          {detail}
        </span>
      )}
    </span>
  );
}

function App() {
  const [results, setResults] = useState([]);
  return (
    <div>
      <SearchBox onSearch={q => setResults(prev => [q, ...prev])} />
      <ul>{results.map((r, i) => <li key={i}>{r}</li>)}</ul>
      <p><HoverCard label="Hover me" detail="Secret tooltip text!" /></p>
    </div>
  );
}

export default App;