Skip to content

Instantly share code, notes, and snippets.

@zheeeng
Created January 18, 2018 11:40
Show Gist options
  • Save zheeeng/3b2a73377d3b76a0f124cbe749edbbed to your computer and use it in GitHub Desktop.
Save zheeeng/3b2a73377d3b76a0f124cbe749edbbed to your computer and use it in GitHub Desktop.
class Refs extends React.PureComponent<IProps> {
private references: React.ReactInstance[] = []
componentDidMount () {
console.log('references', this.references)
}
setRef = (ref: React.ReactInstance) => {
this.references.push(ref)
}
renderChildren = (children: React.ReactNode): React.ReactNode => {
if (Array.isArray(children)) {
return React.Children.map(children, this.renderChildren)
}
if (React.isValidElement(children) && typeof children.type === 'symbol') {
return React.Children.map((children.props as { children: React.ReactNode }).children, this.renderChildren)
}
if (React.isValidElement<{ ref: (ref: React.ReactInstance) => void}>(children)) {
return React.cloneElement(children, { ref: this.setRef })
}
return children
}
render () {
return this.renderChildren(this.props.children) || null
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment