DEV Community

Ayoola Damilare
Ayoola Damilare

Posted on

2

My React Journey: Day 24

Event Handling in React

1. What Are Events in React?
Events are user or system actions (e.g., clicking a button, typing in a field, hovering over an element, etc.). React uses synthetic events, a cross-browser wrapper around the browser’s native events, ensuring consistency and compatibility across different browsers.

2. How Do We Handle Events in React?
Event handling in React involves defining a function (event handler) that gets executed when the event occurs.

Example Syntax:

function handleEvent() {
  console.log('Event handled!');
}

return <button onClick={handleEvent}>Click Me</button>;
Enter fullscreen mode Exit fullscreen mode
  • onClick is the event name.
  • handleEvent is the function executed when the button is clicked.

3. Key Points to Remember

  • Event Names: Use camelCase (e.g., onClick, onChange).
  • Pass Function Reference: Do not invoke the function directly.
  • ✅ onClick={handleEvent}
  • ❌ onClick={handleEvent()}
  • Event handlers can be defined inside or outside the component.

4. Common Events in React

  • onClick: Clicking a button
  • onChange: Typing in an input field
  • onSubmit: Submitting a form
  • onMouseEnter: Hovering over an element
  • onFocus: Focusing on an input field

5. Example with Multiple Events
Student.jsx:

import PropTypes from 'prop-types';

export default function Student(props) {
  // Event Handlers
  function handleClick() {
    alert('Button clicked');
  }

  function handleMouseEnter() {
    console.log('Mouse entered');
  }

  function handleInputChange(event) {
    console.log('Input value:', event.target.value);
  }

  return (
    <div className="student" onMouseEnter={handleMouseEnter}>
      <p>Name: {props.name}</p>
      <p>Age: {props.age}</p>
      <p>Student: {props.isStudent ? 'Yes' : 'No'}</p>
      <input type="text" placeholder="Type something..." onChange={handleInputChange} />
      <button onClick={handleClick}>Click Me</button>
    </div>
  );
}

// PropTypes
Student.propTypes = {
  name: PropTypes.string,
  age: PropTypes.number,
  isStudent: PropTypes.bool,
};

// DefaultProps
Student.defaultProps = {
  name: 'Guest',
  age: 0,
  isStudent: false,
};
Enter fullscreen mode Exit fullscreen mode

6. What's Happening Here?

  • handleClick: Displays an alert when the button is clicked.
  • handleMouseEnter: Logs a message to the console when the mouse enters the div.
  • handleInputChange: Logs the text typed in the input field.

7. Accessing Event Information
React automatically passes the event object to the handler.

function handleClick(event) {
  console.log(event.target); // Logs the element that triggered the event
}

return <button onClick={handleClick}>Click Me</button>;
Enter fullscreen mode Exit fullscreen mode

8. Inline Event Handlers (Optional)
You can define event handlers directly in JSX:

<button onClick={() => console.log('Clicked!')}>Click Me</button>;
Enter fullscreen mode Exit fullscreen mode

Why Avoid Inline Functions?
They create a new function instance every time the component renders, which can impact performance. Use them sparingly.

9. Binding this in Class Components
In class components, bind this to access the component’s context in event handlers:

class App extends React.Component {
  constructor(props) {
    super(props);
    this.handleClick = this.handleClick.bind(this);
  }

  handleClick() {
    console.log('Button clicked!');
  }

  render() {
    return <button onClick={this.handleClick}>Click Me</button>;
  }
}

Enter fullscreen mode Exit fullscreen mode

10. Passing Arguments to Event Handlers
To pass arguments, use an inline arrow function:

function handleClick(name) {
  alert(`Hello, ${name}!`);
}

return <button onClick={() => handleClick('Ayoola')}>Click Me</button>;
Enter fullscreen mode Exit fullscreen mode

Key Takeaways

  • React simplifies event handling with synthetic events for cross-browser compatibility.
  • Always pass a function reference to event handlers.
  • Use event objects to access detailed information about the event.
  • Use inline functions sparingly for performance reasons.

React event handling is fun and powerful! 🎉

Sentry blog image

Identify what makes your TTFB high so you can fix it

In the past few years in the web dev world, we’ve seen a significant push towards rendering our websites on the server. Doing so is better for SEO and performs better on low-powered devices, but one thing we had to sacrifice is TTFB.

Read more

Top comments (0)

Cloudinary image

Zoom pan, gen fill, restore, overlay, upscale, crop, resize...

Chain advanced transformations through a set of image and video APIs while optimizing assets by 90%.

Explore

👋 Kindness is contagious

Discover a treasure trove of wisdom within this insightful piece, highly respected in the nurturing DEV Community enviroment. Developers, whether novice or expert, are encouraged to participate and add to our shared knowledge basin.

A simple "thank you" can illuminate someone's day. Express your appreciation in the comments section!

On DEV, sharing ideas smoothens our journey and strengthens our community ties. Learn something useful? Offering a quick thanks to the author is deeply appreciated.

Okay