Reputation: 1019
I am building a custom component in React Native that will automatically manage the components passed as children.
This component will also add custom props to the children.
One caveat however is that children components are unable to use these props directly; instead, creating a SFC or extending React.Component is necessary in order to access the props
object of those childs.
I was wondering if there is a way to access those added props without doing that?
In the code below, for example, I'd like to be able to access the managerProp
like this:
<ManagerComponent>
<Child onPress={ managerProp.handleOnPress }>
{managerProp.something}
</Child>
</ManagerComponent>
Upvotes: 0
Views: 1299
Reputation: 39192
The way to do this is to have your ManagerComponent
expose a render prop (basically a function it will call to render its children). It can pass in its "extra" props to this function. You can use children as the render prop which leads to something like:
function ManagerComponent({children}) {
const extraProps = {handleOnPress: ..., ...}
// The trick is we call children as a function instead
// of treating it as a component to render
return <div>{children(extraProps)}</div>
}
ManagerComponent.propTypes = { children: PropTypes.func.isRequired }
function Foo() {
return (
<ManagerComponent>
{managerProps => (
<Child onPress={managerProps.handleOnPress}>
{managerProps.something}
</Child>)
}
</ManagerComponent>
)
}
Here is a blog article (not mine) that discusses this concept in more detail.
Upvotes: 1