From f7a5688c950b6b7f95c984082f05ef78492429eb Mon Sep 17 00:00:00 2001 From: John DeSilva Date: Sun, 11 Sep 2016 13:31:07 -0400 Subject: [PATCH] Optionally disable wrappedInstance ref Stateless components cannot use refs, so this adds the withRef option (enabled by default for compatibility) which enables or disables passing the wrappedInstance ref to the wrapped component. Addresses issue #30. Inspired by https://github.com/reactjs/react-redux/commit/2d3d0beade55477b3af65534ceb793db18b25705 --- README.md | 2 ++ index.jsx | 9 +++++++-- 2 files changed, 9 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 6400754..4615be8 100644 --- a/README.md +++ b/README.md @@ -50,6 +50,8 @@ or as an [ES7 class decorator](https://github.com/wycats/javascript-decorators) - `$0.containerStyle` (optional, default `defaultContainerStyle`) - `$0.className` (optional, default `null`) - `$0.elementResize` (optional, default `false`) + - `options.withRef` **[boolean](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Boolean)=** Set true to enable accessing the wrapped instance with + [getWrappedInstance()](https://github.com/digidem/react-dimensions#getwrappedinstance). Disable this when wrapping stateless components, as they cannot use `refs`. (optional, default `true`) **Examples** diff --git a/index.jsx b/index.jsx index e7898e7..f66f434 100644 --- a/index.jsx +++ b/index.jsx @@ -83,6 +83,7 @@ module.exports = function Dimensions ({ containerStyle = defaultContainerStyle, className = null, elementResize = false + withRef = true } = {}) { return (ComposedComponent) => { return class DimensionsHOC extends React.Component { @@ -147,7 +148,10 @@ module.exports = function Dimensions ({ * @return {object} The rendered React component **/ getWrappedInstance () { - this.refs.wrappedInstance + if (!withRef) { + console.warn('You need to enable the `withRef` option to access the wrapped instance') + } + return this.refs.wrappedInstance } render () { @@ -155,6 +159,7 @@ module.exports = function Dimensions ({ if (!containerWidth && !containerHeight) { console.warn('Wrapper div has no height or width, try overriding style with `containerStyle` option') } + const ref = withRef ? 'wrappedInstance' : null return (
{(containerWidth || containerHeight) && @@ -162,7 +167,7 @@ module.exports = function Dimensions ({ {...this.state} {...this.props} updateDimensions={this.updateDimensions} - ref='wrappedInstance' + ref={ref} /> }