Skip to content

Instantly share code, notes, and snippets.

@hypervillain
Created October 16, 2018 17:26
Show Gist options
  • Save hypervillain/71bd536f4576cfcf9057401806e7fcbe to your computer and use it in GitHub Desktop.
Save hypervillain/71bd536f4576cfcf9057401806e7fcbe to your computer and use it in GitHub Desktop.
A generic React component that forwards its ref
import { Component } from 'react';
import PropTypes from 'prop-types';
class ForwardRef extends Component {
static propTypes = {
children: PropTypes.func.isRequired,
ComponentWrapper: PropTypes.string || PropTypes.node,
refPropName: PropTypes.string,
}
static defaultProps = {
ComponentWrapper: 'div',
refPropName: 'parentRef',
};
state = {
ref: null,
};
render() {
const {
children,
refPropName,
ComponentWrapper,
...rest
} = this.props;
return (
<ComponentWrapper
ref={(ref) => {
if (!this.state.ref) {
this.setState({
ref,
});
}
return null;
}}
{...rest}
>
{children({ [refPropName]: this.state.ref })}
</ComponentWrapper>
);
}
}
ForwardRef.defaultProps = {
ComponentWrapper: 'div',
refPropName: 'parentRef',
};
ForwardRef.displayName = 'ForwardRef';
export default ForwardRef;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment