Based on the uploaded 12-page “REACT Events” notes

React Events

Learn how React responds to clicks, typing, form submission, pointer movement, focus, and keyboard actions — using small CSE-friendly examples and interactive demonstrations.

onClickonChangeonSubmit onKeyDowntarget vs currentTargetpreventDefault

Project Setup

The source uses Vite for current React practice. It also notes that older material may show Create React App and older ReactDOM examples.

npm create vite@latest react-events-lab -- --template react
cd react-events-lab
npm install
npm run dev

Tools

VS Code, Node.js LTS and a modern browser.

Browser tools

Open Developer Tools with F12 or Ctrl+Shift+I, then use the Console when an example uses console.log.

1. What is an Event?

An event is an action or occurrence performed by a user for which a program can respond.

Click

A student clicks a button.

Typing

A learner types into a search box.

Form

A student submits a form.

Pointer / Keyboard

The pointer moves or a key is pressed.

React idea: Assign a function to an event prop such as onClick or onChange. The component declares the response instead of manually attaching DOM listeners.
<button onClick={handleClick}>Mark present</button>
<input onChange={handleChange} />
<form onSubmit={handleSubmit}>...</form>

2. Syntax for React Events

React event names use camelCase, unlike HTML’s lowercase event attributes.

Use this in ReactNot this HTML-style spelling
onClickonclick
onMouseEnteronmouseenter
onKeyDownonkeydown
Important: The event prop value must be a function or an expression that produces a function. Do not call the handler while rendering.
function handleClick(event) {
  console.log(event.type);
}

<button type="button" onClick={handleClick}>Save</button>

3. Event Handlers

Named handlers inside a component

export default function App() {
  function downloadNotes() {
    console.log('Notes download started');
  }

  function openHelp() {
    console.log('Help opened');
  }

  return (
    <>
      <button onClick={downloadNotes}>Download notes</button>
      <button onClick={openHelp}>Open help</button>
    </>
  );
}

Each button can have its own named handler.

Interactive notice: multiple event types

Interactive notice

Move over or focus the card

import { useState } from 'react';

export default function App() {
  const [status, setStatus] = useState('Move over or focus the card');

  return (
    <article
      tabIndex="0"
      onMouseEnter={() => setStatus('Pointer entered')}
      onFocus={() => setStatus('Card focused')}
      onKeyDown={e => setStatus(`Key: ${e.key}`)}
    >
      <h2>Interactive notice</h2>
      <p>{status}</p>
    </article>
  );
}
Event flow: Event → Handler → State changes → UI changes.

4. The Event Object

React passes an event object to a handler when an event occurs. It contains useful information about what happened.

event.type

The event type, such as change or click.

event.target

The element that actually triggered the event.

event.currentTarget

The element whose handler is currently running.

event.key

The key value for keyboard events.

event.target.value

The current text/value for form inputs.

Try target vs currentTarget

Parent section
Click the nested button to compare the two properties.
export default function App() {
  function handleClick(event) {
    console.log('target:', event.target.tagName);
    console.log('currentTarget:', event.currentTarget.tagName);
  }

  return (
    <section onClick={handleClick}>
      <button>Click nested button</button>
    </section>
  );
}

Keyboard information

Type in the box
function handleKeyDown(event) {
  if (event.key === 'Enter') {
    setMessage('Search submitted with Enter');
  }
}

5. Common React Events

React supports the major browser event categories used in web applications.

Event propTypical elementUse
onClickbutton, links, controlsA user activates a control.
onChangeinput, select, textareaA form value changes.
onSubmitformA form is submitted.
onKeyDowninput, document-like controlsA key is pressed.
onFocus / onBlurform controlsFocus enters or leaves.
onMouseEnter / onMouseLeaveinteractive regionsPointer enters or leaves.
Other categories in the source: clipboard, drag, touch, pointer and wheel events are also available.

6. Mouse Enter, Focus & Blur

Mouse enter and leave

Web Lab

Move the pointer here

export default function App() {
  const [hint, setHint] = useState('');

  return (
    <article
      onMouseEnter={() => setHint('React lab begins at 10 AM')}
      onMouseLeave={() => setHint('')}
    >
      <h2>Web lab</h2>
      <p>{hint || 'Move the pointer here'}</p>
    </article>
  );
}

Focus and blur validation

Leave the field to validate it.
const [error, setError] = useState('');

<input
  id="email"
  onBlur={e =>
    setError(
      e.target.value.includes('@')
        ? ''
        : 'Enter a valid email'
    )
  }
/>
Source note: A later line shows a stricter pattern that also checks the part after @ for a dot: e.target.value.includes('@') && e.target.value.split('@')[1]?.includes('.').

7. Event Propagation & preventDefault

In bubbling, an event starts at the target and then moves upward through ancestors, so both a button and its parent may respond.

stopPropagation()

Use it when the parent must not receive the event from the inner control.

preventDefault()

Use it when React should manage an action instead of allowing the browser's default action.

Propagation demo

React Foundations

Click the card to open it. The inner button can stop the event from reaching the card.

No action yet.
function openCard() {
  alert('Card opened');
}

function addBookmark(event) {
  event.stopPropagation();
  alert('Bookmarked');
}

return (
  <article onClick={openCard}>
    <h2>React Foundations</h2>
    <button onClick={addBookmark}>Bookmark</button>
  </article>
);

Prevent a form reload

The page will stay in place when you submit.
function handleSubmit(event) {
  event.preventDefault();
  setNotice('Notice submitted without reloading the page');
}
Common pitfall: A button inside a form defaults to submit. Use type="button" for non-submit buttons.

8. Passing Data to Handlers

Sometimes a handler needs an extra value such as a student ID, product ID or assignment ID. Use an arrow wrapper or bind to pass that value. Do not invoke the handler during rendering.

<button onClick={() => deleteItem(item.id)}>Delete</button>

<button onClick={handleDelete.bind(null, item.id)}>Delete</button>

Interactive assignment list

    Select an assignment.
    const assignments = [
      { id: 1, title: 'JS basics' },
      { id: 2, title: 'React lab' }
    ];
    
    function selectAssignment(id) {
      setSelected(`Assignment ${id} selected`);
    }
    
    {assignments.map(item => (
      <li key={item.id}>
        {item.title}
        <button onClick={() => selectAssignment(item.id)}>Select</button>
      </li>
    ))}
    List reminder: Use a stable key for the list and pass the id through the arrow function.

    9. Events in Function Components & Controlled Inputs

    Function components define event handlers as ordinary JavaScript functions inside the component. They can read props, call state setters and use the event object.

    Searching for: all students
    import { useState } from 'react';
    
    function App() {
      const [query, setQuery] = useState('');
    
      function handleChange(event) {
        setQuery(event.target.value);
      }
    
      return (
        <>
          <label htmlFor="q">Search</label>
          <input id="q" value={query} onChange={handleChange} />
          <p>Searching for: {query || 'all students'}</p>
        </>
      );
    }
    
    export default App;
    Good practice from the source: Keep handlers short, move reusable logic into clearly named functions, and use memoization only after measuring a real performance issue.

    10. Events in Class Components

    Class components handle events through methods. A method passed directly to a child can lose its this context because it may be invoked as a plain function.

    Class handler with bind

    import { Component } from 'react';
    
    export default class App extends Component {
      constructor(props) {
        super(props);
        this.state = { count: 0 };
        this.handleClick = this.handleClick.bind(this);
      }
    
      handleClick() {
        this.setState(previous => ({
          count: previous.count + 1
        }));
      }
    
      render() {
        return (
          <>
            <p>Clicks: {this.state.count}</p>
            <button onClick={this.handleClick}>Add click</button>
          </>
        );
      }
    }

    Bind-style class counter

    Clicks: 0

    Class-field arrow handler

    import { Component } from 'react';
    
    export default class App extends Component {
      state = { status: 'Waiting' };
    
      handleClick = () => {
        this.setState({ status: 'Submitted' });
      };
    
      render() {
        return (
          <>
            <p>{this.state.status}</p>
            <button onClick={this.handleClick}>Submit</button>
          </>
        );
      }
    }

    Class-field arrow demo

    Waiting
    Tooling note: The source says older tooling may prefer constructor binding instead of relying on class fields.

    Source Visual References

    The uploaded document contains screenshots illustrating browser-console output and small event examples. They are preserved here as visual references.

    11. Quick Check

    1. Which spelling is the React event prop?
    2. What does event.target identify?
    3. Which method prevents a normal form submission action?
    4. Which event is commonly used when an input value changes?

    Quick Revision

    Event

    An action or occurrence that a program can respond to.

    Handler

    A function React calls when the event occurs.

    Event object

    Carries details such as type, target, key and form values.

    Propagation

    Bubbling lets the event move from target to ancestors.

    preventDefault()

    Stops the browser's default action when React should handle it.

    stopPropagation()

    Stops the event from reaching an ancestor handler.