Skip to content

Commit

Permalink
Use forwardRef to pass on the ref (#182)
Browse files Browse the repository at this point in the history
  • Loading branch information
chinmaychaudhary authored Jul 22, 2021
1 parent 86e936b commit 24964b4
Show file tree
Hide file tree
Showing 3 changed files with 24 additions and 8 deletions.
6 changes: 3 additions & 3 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -33,10 +33,11 @@
"main": "src/index.js",
"dependencies": {
"hoist-non-react-statics": "^3.0.0",
"loader-utils": "^1.2.3"
"loader-utils": "^1.2.3",
"prop-types": "^15.7.2"
},
"peerDependencies": {
"react": "^16.3.0",
"react": "^16.8.2",
"react-dom": "^16.8.2"
},
"devDependencies": {
Expand All @@ -56,7 +57,6 @@
"husky": "^1.3.1",
"jest": "^24.1.0",
"prettier": "^1.16.4",
"prop-types": "^15.7.2",
"react": "^16.8.2",
"react-dom": "^16.8.2",
"rollup": "^1.2.1",
Expand Down
21 changes: 17 additions & 4 deletions src/withStyles.js
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
*/

import React from 'react'
import PropTypes from 'prop-types'
import hoistStatics from 'hoist-non-react-statics'

import StyleContext from './StyleContext'
Expand All @@ -27,17 +28,29 @@ function withStyles(...styles) {
}

render() {
return <ComposedComponent {...this.props} />
const { __$$withStylesRef, ...props } = this.props
return <ComposedComponent ref={__$$withStylesRef} {...props} />
}
}

const displayName = ComposedComponent.displayName || ComposedComponent.name || 'Component'

WithStyles.displayName = `WithStyles(${displayName})`
WithStyles.propTypes = {
__$$withStylesRef: PropTypes.func,
}
WithStyles.defaultProps = {
__$$withStylesRef: undefined,
}
WithStyles.contextType = StyleContext
WithStyles.ComposedComponent = ComposedComponent

return hoistStatics(WithStyles, ComposedComponent)
const ForwardedWithStyles = React.forwardRef((props, ref) => (
<WithStyles {...props} __$$withStylesRef={ref} />
))

ForwardedWithStyles.ComposedComponent = ComposedComponent
ForwardedWithStyles.displayName = `WithStyles(${displayName})`

return hoistStatics(ForwardedWithStyles, ComposedComponent)
}
}

Expand Down
5 changes: 4 additions & 1 deletion test/insertCss.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,10 @@ describe('insertCss(styles, options)', () => {
it('Should insert and remove multiple <style> elements for a single module', () => {
const css1 = 'body { color: red; }'
const css2 = 'body { color: blue; }'
const removeCss = insertCss([[1, css1], [1, css2]])
const removeCss = insertCss([
[1, css1],
[1, css2],
])
let style = global.document.getElementsByTagName('style')
expect(style).toHaveLength(2)
expect(style[0].textContent).toBe(css1)
Expand Down

0 comments on commit 24964b4

Please sign in to comment.