Blog>
Snippets

Implementing the Render Props Pattern for Reusable Logic

Demonstrate the use of a render prop component in Next.js 14, which allows for sharing reusable functionality between components.
// MouseTracker component that uses the render prop pattern to provide its state to children

class MouseTracker extends React.Component {
  constructor(props) {
    super(props);
    this.state = { x: 0, y: 0 };
  }
  
  handleMouseMove = (event) => {
    this.setState({
      x: event.clientX,
      y: event.clientY
    });
  };
  
  render() {
    return (
      <div style={{ height: '100%' }} onMouseMove={this.handleMouseMove}>
        {this.props.children(this.state)}
      </div>
    );
  }
}
This is a MouseTracker class in React which we are going to use in the Next.js. This component uses the render props pattern by accepting a function as the 'children' prop, which allows consumers of the component to decide how to render the UI based on the mouse's position. The component listens for mouse move events and updates its state accordingly, then calls the children function with the updated state.
// Example of usage within a Next.js page/component

import React from 'react';
import MouseTracker from './MouseTracker';

const MouseAwareComponent = () => (
  <MouseTracker>
    {({ x, y }) => (
      <h1>The mouse position is ({x}, {y})</h1>
    )}
  </MouseTracker>
);

export default MouseAwareComponent;
This shows an example of how to use the MouseTracker component within a Next.js page or component. MouseAwareComponent is a functional component that includes MouseTracker. Inside the MouseTracker's children prop, it provides a function that takes the mouse position as parameters, and renders a heading displaying the current mouse coordinates. This demonstrates how the rendered output can be customized using the render props pattern.