How To Handle Events In React? Complete Example

Handling Events in React

In React, handling events is similar to HTML, but there are some key differences:

  • Event names are written in camelCase
  • You pass a function instead of a string

Example:

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

Handling Click Events

function handleClick() {
  alert("Button Clicked!");
}

function App() {
  return <button onClick={handleClick}>Click Me</button>;
}

Handling Input Changes

function App() {
  const [name, setName] = React.useState("");

  const handleChange = (event) => {
    setName(event.target.value);
  };

  return (
    <div>
      <input type="text" value={name} onChange={handleChange} />
      <p>Hello, {name}</p>
    </div>
  );
}

Handling Form Submissions

function App() {
  const handleSubmit = (event) => {
    event.preventDefault();
    alert("Form submitted!");
  };

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

Key Points

  • Use camelCase for event handlers
  • Pass a function reference, not a call
  • Use event.preventDefault() for forms
  • Functional components often use hooks to manage state

Conclusion

Handling events in React is essential for making applications interactive and dynamic. Once you master event handling, your apps become much more responsive.


Citations

https://savanka.com/category/learn/react/
https://www.w3schools.com/REACT/DEFAULT.ASP

Leave a Comment

Comments

No comments yet. Why don’t you start the discussion?

Leave a Reply

Your email address will not be published. Required fields are marked *