Logo
READLEARNKNOWCONNECT
Back to Lessons

    Page

  • - What Are Events?
  • - Handling Click Events
  • - Handling Input Events
  • - Prevent Default Behavior
  • - Mini Project Step

7. Handling Events in React

Level: BeginnerDuration: 16m

What Are Events?

Events are actions that happen in the browser — things like clicking a button, typing in an input box or submitting a form. React lets us handle these events easily using event handlers.

Handling Click Events

To handle a click in React, you pass a function to the `onClick` event. The function runs when the element is clicked.

jsx
function ClickExample() {
  function handleClick() {
    alert('Button clicked!')
  }

  return <button onClick={handleClick}>Click Me</button>
}

Notice we passed the function name `handleClick` without calling it. If you do `onClick={handleClick()}`, it will run immediately instead of waiting for a click.

Handling Input Events

To get the value from an input field, use the `onChange` event. It gives you access to what the user is typing.

jsx
function InputExample() {
  function handleChange(event) {
    console.log(event.target.value)
  }

  return <input onChange={handleChange} placeholder="Type something" />
}

`event.target.value` gives you the latest value inside the input field.

Prevent Default Behavior

Some events have default actions, like a form trying to reload the page when submitted. To stop that, use `event.preventDefault()`.

jsx
function FormExample() {
  function handleSubmit(event) {
    event.preventDefault()
    alert('Form submitted!')
  }

  return (
    <form onSubmit={handleSubmit}>
      <button type="submit">Submit</button>
    </form>
  )
}

Mini Project Step

Update your `App.jsx` to include a button that logs a message to the console when clicked and an input field that displays what the user types in real time.

jsx
// App.jsx
import { useState } from 'react'

function App() {
  const [message, setMessage] = useState('')

  function handleButtonClick() {
    console.log('Hello from React!')
  }

  function handleInputChange(event) {
    setMessage(event.target.value)
  }

  return (
    <div>
      <button onClick={handleButtonClick}>Click Me</button>

      <input
        type="text"
        placeholder="Type a message"
        onChange={handleInputChange}
      />

      <p>You typed: {message}</p>
    </div>
  )
}

export default App