Skip to content
Today's Tech Byte: Advanced configuration with render props

Today's Tech Byte: Advanced configuration with render props

Posted on:October 30, 2023

In the previous chapter, we learned how to use the Element as props pattern to solve issues like component configuration. But what happens when we need to configure the component in a more advanced way?

Render props for rendering Elements

In case where a component wants to pass state to another component, we can use the render props pattern. The idea is to pass a function as a prop to the component. This function will be called by the component to render the Element.

// instead of "icon" that expects an Element
// we're receiving a function that returns an Element
const Button = ({ renderIcon }) => {
  const [isEnabled, setIsEnabled] = useState(false);
  // and then just calling this function where the icon should be rendered
  return <button>Submit {renderIcon({ isEnabled })}</button>;

We can then use the Button component like this:

<Button renderIcon={({ isEnabled }) => <Icon isEnabled={isEnabled} />} />

Same logic can been applied on Children as props pattern, because if you remember, children are nothing more than props.

Just use the damn hook

You may wondering why not just use hooks to solve this problem? Well, in modern day React, hooks are the way to go. But this pattern is still useful in some cases.

For example when the logic is attached to a DOM element.

const Button = ({ renderIcon }) => {
  const [isClicked, setIsClicked] = useState(false);

  return <button>Submit {renderIcon({ isClicked })}</button>;

That’s it for today’s tech byte.

If you have any suggestions or questions, feel free to reach out to me on Twitter or LinkedIn.

P.S. this post is inspired by the book, but it’s not a summary of it. I’m just sharing what I learned from it. If you want to learn more about React, I highly recommend you to read it.