Logo

dev-resources.site

for different kinds of informations.

My React Journey: Day 24

Published at
12/23/2024
Categories
webdev
react
mobile
deedoth
Author
ayoola_damilare_212d5bde0
Categories
4 categories in total
webdev
open
react
open
mobile
open
deedoth
open
Author
25 person written this
ayoola_damilare_212d5bde0
open
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! ๐ŸŽ‰

Featured ones: