render-props icon indicating copy to clipboard operation
render-props copied to clipboard

Handling anything (not just component or function)

Open Offirmo opened this issue 6 years ago • 2 comments

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?

Offirmo avatar Jul 18 '18 03:07 Offirmo

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

Offirmo avatar Jul 18 '18 04:07 Offirmo

Another way is adding a check before using this library:

if (React.isValidElement(children)) return children;
else return renderProps(component || children || render, props);

peteruithoven avatar Jan 25 '19 15:01 peteruithoven