React Render Props

/ Reading time: 4 minutes

The React documentation is really good, but being pretty new to React - particularly when going beyond the basics - I found the section on Render Props hard to follow.

I felt that a further simplified example would have been helpful, and this is my attempt at that.

The issue I was trying to solve that led me to render props was:

I had previously put this together using children to pass the figure being shown, and while this gave me the flexibility to pass the variety formats I needed, it caused problems when I needed to use a function on a number to apply formatting, especially when this number could be null. I had to use a fair amount of logic in my JSX to make it work, and I really didn’t want to diversify the currency and percentage functions. It was a mess.

These kinds of problems are hard to solve when you’re teaching yourself. Knowing how to google effectively is a key skill in being a developer, and fortunately I stumbled upon render props.

What are render props?

Render props allow you to pass a template as a prop, and render that inside the parent component.

That’s a terrible explanation that I have tried to rewrite a dozen times, so let’s look at an example.

<NaLabel render={value => <span>{currency(value)}</span>} value={paymentAmount} />

(Apologies for the poor syntax highlighting; I made this before JSX was a thing, but a whole new site is in progress so it’ll be fixed eventually.)

Here we are using the NaLabel component and passing the value we want to show as a prop. Our render prop contains a function that returns a template. You could use another component or any other valid JSX in the template.

const NaLabel = ({ render, value }) => {
  const isNull = value === null;
  
  if (isNull) {
    return <abbr title="Not Applicable">n/a</abbr>;
  }
  return render(value)
};

Let’s go over what this component does:

  1. Check if the value being passed is null. In this case, zero is a valid figure so we have to check for null specifically rather than a falsey value.
  2. If the value is null, show the ‘Not Applicable’ abbreviation.
  3. If the value is not null, use our render prop passing in the value we want shown.

This is a really stripped back example of using render props, but it is solving a real issue I had, even if this is a reduced example.

I’m sure I’ll run in to far more complex and powerful uses, but I hope this guide helps someone else who is confused by the official docs.