Passing Elements as Props in React

I like this nuanced post by David Barral in which he goes over all the options on how to configure a Confirm component: what exactly do you pass in as props.

In this story we are going to see a simple technique that allows you to write friendly customizable components with simple APIs, just by using the basic React building blocks: the element.

The result finds the middle ground between “props explosion” (one prop per customisable part) and render props:

// Component
const Confirm = ({
  acceptButton = <Button>Ok</Button>,
  rejectButton = <Button>Cancel</Button>,
}) => (
  <div className="confirm">
    <div className="confirm-header">
    <div className="confirm-content">{children}</div>
    <div className="confirm-footer">
      {React.cloneElement(acceptButton, { className: "accept-btn", onClick: onAccept })}
      {React.cloneElement(rejectButton, { className: "reject-btn", onClick: onReject })}

// Usage
  onAccept={() => {}}
  onReject={() => {}}
  You sure?

Passing Elements as Props in React →

Published by Bramus!

Bramus is a frontend web developer from Belgium, working as a Chrome Developer Relations Engineer at Google. From the moment he discovered view-source at the age of 14 (way back in 1997), he fell in love with the web and has been tinkering with it ever since (more …)

Leave a comment

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.