For example, in the @headless-ui/react
library, the Listbox.Option
can pass down the values of its internal props through the following:
<Listbox.Option>
{({ selected }) => (/* some component here */)}
</Listbox.Option>
What is this called, and how can one write code that achieves a similar function?
CodePudding user response:
It's called a render prop.
You can easily make your own render props by using the children
component as a function.
function MyComponent({ children }) {
// ...
return <div>{children(...)}</div>
}
<MyComponent>
{(...) => ...}
</MyComponent>
CodePudding user response:
This pattern is named rather descriptively: Function-as-Child-Component. It's a variation on render-props.
Authoring a component that works in this way can be as simple as literally calling the children
prop passed in (e.g. children()
), though it's recommended to at least run React.Children.only(children)()
to ensure that children
is not an array.
React.Children.only documentation here, for reference.