DEV Community

Levi ᕙ(⇀‸↼‶)ᕗ
Levi ᕙ(⇀‸↼‶)ᕗ

Posted on

What is a Render Prop?

This is from my React newsletter, you can subscribe here

What is a render prop and why should you care?

It's funny, I have actually been using render props since sometime in 2016, but I didn't know that was uncommon. I actually thought it was just a normal thing everyone did in React. I was calling them "Component Props" when teaching them to my team back then. And thats because that is essentially all they are. A component passed in as a prop. They might seem more confusing then that, but thats just the arrow syntax playing tricks on you. Let me demonstate.

const SimpleComp = data => <h2>{data}</h2>;
const CompWithRenderProp = ({ RenderProp }) => (
  <div>
    <h1>Hey You!</h1>
    {RenderProp("from Comp")}
  </div>
);
const App = () => {
  return (
    <div className="App">
      <CompWithRenderProp RenderProp={SimpleComp} />
    </div>
  );
};

Now you may be thinking "When would I ever want to do that". Well render props can be used in place of any higher order component. That's right, literally every higher order component can be written with render props instead!

I think that is really cool because I don't really like writing higher order components. I find them confusing to be frank, where render props come very natural to me.

I often use this pattern for things like modals. I pass a close function to the component so I can choose to close it via an "X" or a "Cancel" button or after submitting without duplicating "close" logic.

A common way of using render props is by taking advantage of the children prop. We could have written the above code like so.

const CompWithRenderProp = ({ children }) => (
  <div>
    <h1>Hey You!</h1>
    {children("from Comp")}
  </div>
);
const App = () => {
  return (
    <div className="App">
      <CompWithRenderProp >
      {data => <h2>{data}</h2>}
      </CompWithRenderProp>
    </div>
  );
};

Weekly take-aways

  1. Every higher order component can be re-created using render props.
  2. Render props are just components passed as a prop.

Subscribe to my newsletter for more content like this.
Newsletter

Top comments (0)