02Geek HTML5 and JavaScript, TypeScript, React, Flash, ActionScript online School
Previous VideoPrevious Video

005.003. Bubbling events in React

Tutorial: Bubbling Events in React

In this tutorial, we’ll dive into event bubbling and handling events in React, a crucial concept for building dynamic and efficient applications. By the end, you'll have a clear understanding of how to use callbacks for event handling and how to manage application state centrally.


1. Introduction to Event Handling in React

React handles events differently than traditional DOM-based JavaScript:

  • React does not use the native DOM event bubbling by default.
  • Events are handled through callbacks passed via props.
  • This allows greater control and makes the state and event propagation more predictable.

2. Structuring the Navigation Model

To make our navigation dynamic:

  • Create a Navigation Model:
    • Define an array containing the links and names for each menu item.
    • Example:
      const navModel = [
        { link: '#portfolio', name: 'Portfolio' },
        { link: '#about', name: 'About' },
        { link: '#contact', name: 'Contact' }
      ];
      
  • Pass this model to the Nav component as a prop for rendering.

3. Dynamic Rendering of Navigation Items

Instead of hardcoding the menu items:

  1. Loop Through the Navigation Model: Use Array.prototype.map() to iterate over the model and generate NavItem components dynamically.
    const navItems = navModel.map((item, index) => (
      <NavItem key={index} link={item.link} name={item.name} />
    ));
    
  2. Render the Items: Place the generated NavItem components in your Nav component:
    <ul>{navItems}</ul>
    

4. Capturing Events with Callbacks

To handle menu clicks:

  1. Add an onClick Callback in the Nav Component:

    function Nav({ data, onClick }) {
      return (
        <ul>
          {data.map((item, index) => (
            <NavItem key={index} {...item} onClick={onClick} />
          ))}
        </ul>
      );
    }
    
  2. Define the Callback in the Parent Component: In your App component or higher level:

    function handleLinkClick(event) {
      event.preventDefault(); // Prevents default anchor behavior
      console.log('Navigating to:', event.target.href);
    }
    

    Pass handleLinkClick as a prop to the Nav component.

  3. Pass Down to Individual Items: In the NavItem component, bind the click handler:

    function NavItem({ link, name, onClick }) {
      return (
        <li>
          <a href={link} onClick={onClick}>
            {name}
          </a>
        </li>
      );
    }
    

5. Binding Context with .bind()

React requires explicit binding for event handlers to ensure the this keyword points to the correct context:

  • In class components, bind the handler in the constructor:
    constructor(props) {
      super(props);
      this.handleLinkClick = this.handleLinkClick.bind(this);
    }
    
  • Alternatively, use arrow functions in modern React:
    onClick={(e) => handleLinkClick(e)}
    

6. Preventing Default Behavior

To stop the browser from navigating immediately:

  • Use event.preventDefault() in the click handler.
  • Example:
    function handleLinkClick(event) {
      event.preventDefault();
      console.log('Custom navigation logic here');
    }
    

7. Centralizing State Management

For large-scale applications:

  • Avoid placing state in every component.
  • Centralize state management in the top-level App component.
  • Use props to pass down state or state-modifying callbacks.

Example:

<App>
  <Nav data={navModel} onClick={handleLinkClick} />
</App>

Alternative Approaches in 2024

  • React Hooks:
    • Use useState and useEffect for managing state and side effects.
    • Replace class components with functional components for cleaner syntax.
  • React Context API:
    • Share state and handlers across deeply nested components without prop drilling.
  • State Management Libraries:
    • For larger applications, consider Redux or Recoil for centralizing state.

Conclusion

This tutorial covered:

  • React’s approach to event bubbling.
  • Creating dynamic navigation.
  • Centralizing state for better app scalability.

In the next lesson, we’ll merge the model with the view to create a cohesive dynamic system. Stay tuned! 🚀

Preparing for Isomorphic JavaScript

Learn idiomatic JavaScript concepts to prepare for building a single-page application. Discover how to separate logic from view for server-side and client-side compatibility.

7:10

Building out the site Navigation

Learn to set up dynamic navigation in React for a single-page application. This tutorial covers reusable navigation components, dynamic links, and default props.

07:13

005.003. Bubbling events in React

Explore React event handling and bubbling with callbacks for scalable SPA development. Learn best practices for dynamic state management.

12:58

Merging Our Model with Our View – React SPA Development

Learn how to connect your model and view using a controller in this step of building a React Single Page Application. Organize your data, define dynamic views, and integrate them seamlessly.

08:25

Making Things Dynamic with Maps

Learn to use the ES6 Map API in React to make your SPA dynamic and scalable by configuring logic for components like the footer.

05:07