What Are React Render Props? Complete Example Tutorial Guide

What Are Render Props?

Render Props is a technique for sharing code between components using a prop whose value is a function.
It allows dynamic rendering and logic reuse.


Basic Syntax

<Component render={(data) => <ChildComponent data={data} />} />

Example: Mouse Tracker

import React from "react";

class MouseTracker extends React.Component {
  state = { x: 0, y: 0 };

  handleMouseMove = (e) => {
    this.setState({ x: e.clientX, y: e.clientY });
  };

  render() {
    return (
      <div style={{ height: "100vh" }} onMouseMove={this.handleMouseMove}>
        {this.props.render(this.state)}
      </div>
    );
  }
}

function App() {
  return (
    <MouseTracker render={({ x, y }) => <h2>Mouse at ({x}, {y})</h2>} />
  );
}

✅ The render prop lets the parent dynamically decide what to render.


Key Points

  • render prop is a function returning JSX
  • Useful for logic reuse like mouse position, form handling, data fetching
  • Can replace HOCs in some scenarios
  • Works in class and functional components

Conclusion

Render Props allow flexible, reusable logic in React components, making your code modular and maintainable.


Citations

https://savanka.com/category/learn/react/
https://www.w3schools.com/REACT/DEFAULT.ASP

Leave a Comment

Comments

No comments yet. Why don’t you start the discussion?

Leave a Reply

Your email address will not be published. Required fields are marked *