Skip to content

Instantly share code, notes, and snippets.

@EnixCoda
Created September 22, 2018 06:23
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save EnixCoda/212b609a94a948568762bee161a0bef2 to your computer and use it in GitHub Desktop.
Save EnixCoda/212b609a94a948568762bee161a0bef2 to your computer and use it in GitHub Desktop.
turn ref into render props
class _ControllerX extends React.Component {
static propTypes = {
forwardRef: PropTypes.func
}
ref = r => this.r = r
someCallback() {
this.r.method()
}
render() {
return React.cloneElement(this.props.children, {
ref: r => {
this.props.forwardRef(r)
this.ref(r)
},
})
}
}
const ControllerX = React.forwardRef((props, ref) => <_ControllerX {...props} forwardRef={ref} />)
const usage1 = (
<ControllerA>
<ControllerB>
<View />
</ControllerB>
</ControllerA>
)
// --------------------------------
function createRenderPropsForRef(BaseComponentClass) {
return class RenderProps extends React.Component {
render() {
const { children, ...otherProps } = this.props
return (
<React.Fragment>
<BaseComponentClass {...otherProps} />
{this.props.children(this)}
</React.Fragment>
)
}
}
}
class ControllerX extends React.Component {
someCallback() {
this.props.view.method()
}
render() {
// you can also render anything you want
return null
}
}
const ViewAsRenderProps = createRenderPropsForRef(ViewComponent)
const usage2 = (
<ViewAsRenderProps>
{instanceOfView => (
<React.Fragment>
<ControllerA view={instanceOfView} />,
<ControllerB view={instanceOfView} />,
</React.Fragment>
)}
</ViewAsRenderProps>
)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment