render-props
render-props copied to clipboard
Handling anything (not just component or function)
I'm not 100% sure, but when using the "children" mode:
<foo>
Hello
</foo>
with a render like that:
const content = this.props.children || this.props.render
return renderProps(content, this.props)
It fails pitifully with Cannot read property 'render' of undefined
.
My guess is that's coming from the component detection in render-props.
Could we make it work?
What I ended up implementing:
const { children, render, ...props } = this.props
const ComponentOrFunctionOrAny = children || render || DEFAULT_CONTENT
// is it a react component?
if (ComponentOrFunctionOrAny.render || (ComponentOrFunctionOrAny.prototype && ComponentOrFunctionOrAny.prototype.render))
return <ComponentOrFunction {...props} />
// is it a render function?
if (typeof ComponentOrFunctionOrAny === 'function')
return ComponentOrFunctionOrAny({
...(ComponentOrFunctionOrAny.defaultProps || {}),
...props,
})
// must be null or a string
return ComponentOrFunctionOrAny
Maybe naive but it works in my use case.
[edit] removed a wrong Component detection
Another way is adding a check before using this library:
if (React.isValidElement(children)) return children;
else return renderProps(component || children || render, props);