SmartCodingTips

πŸ–±οΈ Handling Events in React

React uses a slightly different approach to handling browser events. You can pass event handlers as props directly into elements using camelCase syntax.


πŸ“Œ Basic Event Example


function ClickButton() {
  function handleClick() {
    alert("Button was clicked!");
  }

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

⚑ Inline Event Handler

You can define the function directly inside the JSX:


<button onClick={() => alert("Clicked!")}>Click</button>

πŸ“¨ Accessing Event Object

React automatically passes the event object to your handler:


function handleClick(event) {
  console.log(event.target);
}

🚫 Preventing Default Behavior


function MyForm() {
  function handleSubmit(e) {
    e.preventDefault();
    alert("Form submitted!");
  }

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

🧠 No Need for Binding

In modern React (with function components), you don’t need to bind this like in class components. Arrow functions preserve scope naturally.

βœ… Best Practices

  • Use named functions for better readability and debugging.
  • Avoid inline functions if performance is a concern (e.g. large lists).
  • Use preventDefault() for forms or anchor tags when needed.

πŸ“‹ Summary

  • Use onClick, onChange, onSubmit, etc. with camelCase syntax.
  • Arrow functions keep this binding clean.
  • React normalizes events across browsers.