Skip to content

Commit

Permalink
Optionally disable wrappedInstance ref
Browse files Browse the repository at this point in the history
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 digidem#30.
Inspired by reduxjs/react-redux@2d3d0be
  • Loading branch information
Aesthetikx committed Sep 11, 2016
1 parent 9eaf76d commit f7a5688
Show file tree
Hide file tree
Showing 2 changed files with 9 additions and 2 deletions.
2 changes: 2 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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**

Expand Down
9 changes: 7 additions & 2 deletions index.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -83,6 +83,7 @@ module.exports = function Dimensions ({
containerStyle = defaultContainerStyle,
className = null,
elementResize = false
withRef = true
} = {}) {
return (ComposedComponent) => {
return class DimensionsHOC extends React.Component {
Expand Down Expand Up @@ -147,22 +148,26 @@ 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 () {
const {containerWidth, containerHeight} = this.state
if (!containerWidth && !containerHeight) {
console.warn('Wrapper div has no height or width, try overriding style with `containerStyle` option')
}
const ref = withRef ? 'wrappedInstance' : null
return (
<div className={className} style={containerStyle} ref='container'>
{(containerWidth || containerHeight) &&
<ComposedComponent
{...this.state}
{...this.props}
updateDimensions={this.updateDimensions}
ref='wrappedInstance'
ref={ref}
/>
}
</div>
Expand Down

0 comments on commit f7a5688

Please # to comment.