Skip to content

Commit 5a08c12

Browse files
committed
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 reduxjs/react-redux@2d3d0be
1 parent 04f36ee commit 5a08c12

File tree

2 files changed

+9
-2
lines changed

2 files changed

+9
-2
lines changed

README.md

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -54,6 +54,8 @@ or as an [ES7 class decorator](https://github.com/wycats/javascript-decorators)
5454
- `options.className` **[string](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String)=** Control the class name set on the wrapper `<div>`
5555
- `options.elementResize` **[boolean](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Boolean)=** Set true to watch the wrapper `div` for changes in
5656
size which are not a result of window resizing - e.g. changes to the flexbox and other layout. (optional, default `false`)
57+
- `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
58+
[getWrappedInstance()](https://github.com/digidem/react-dimensions#getwrappedinstance). Disable this when wrapping stateless components, as they cannot use `refs`. (optional, default `true`)
5759

5860
**Examples**
5961

index.jsx

Lines changed: 7 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -77,7 +77,8 @@ module.exports = function Dimensions ({
7777
getDimensions = defaultGetDimensions,
7878
debounce = 0,
7979
debounceOpts = {},
80-
elementResize = false
80+
elementResize = false,
81+
withRef = true
8182
} = {}) {
8283
return (ComposedComponent) => {
8384
return class DimensionsHOC extends React.Component {
@@ -152,6 +153,9 @@ module.exports = function Dimensions ({
152153
* @return {object} The rendered React component
153154
**/
154155
getWrappedInstance () {
156+
if (!withRef) {
157+
console.warn('You need to enable the `withRef` option to access the wrapped instance')
158+
}
155159
return this.refs.wrappedInstance
156160
}
157161

@@ -166,14 +170,15 @@ module.exports = function Dimensions ({
166170
height: 0,
167171
width: 0
168172
}
173+
const ref = withRef ? 'wrappedInstance' : null
169174
return (
170175
<div style={wrapperStyle} ref='wrapper'>
171176
{(containerWidth || containerHeight) &&
172177
<ComposedComponent
173178
{...this.state}
174179
{...this.props}
175180
updateDimensions={this.updateDimensions}
176-
ref='wrappedInstance'
181+
ref={ref}
177182
/>
178183
}
179184
</div>

0 commit comments

Comments
 (0)