Skip to content

Commit 220e2f0

Browse files
author
Austin Wood
committed
[withStyles] Conditionally forward ref to inner component
React.forwardRef was added in React 16.3, but since this package still supports older versions of React, we conditionally fork the application of the forwarded ref. We will remove the fork in favor of always forwarding the ref in a later breaking change version. context: #240 (comment)
1 parent fdff766 commit 220e2f0

File tree

1 file changed

+20
-5
lines changed

1 file changed

+20
-5
lines changed

src/withStyles.jsx

Lines changed: 20 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@
33
import React from 'react';
44
import hoistNonReactStatics from 'hoist-non-react-statics';
55
import getComponentName from 'airbnb-prop-types/build/helpers/getComponentName';
6+
import ref from 'airbnb-prop-types/build/ref';
67

78
import EMPTY_STYLES_FN from './utils/emptyStylesFn';
89
import withPerf from './utils/perf';
@@ -232,8 +233,10 @@ export function withStyles(
232233

233234
return (
234235
<WrappedComponent
235-
ref={forwardedRef}
236-
{...rest}
236+
// TODO: remove conditional once breaking change to only support React 16.3+
237+
// ref: https://github.com/airbnb/react-with-styles/pull/240#discussion_r533497857
238+
ref={typeof React.forwardRef === 'undefined' ? undefined : forwardedRef}
239+
{...(typeof React.forwardRef === 'undefined' ? this.props : rest)}
237240
{...{
238241
[themePropName]: theme,
239242
[stylesPropName]: styles,
@@ -244,9 +247,21 @@ export function withStyles(
244247
}
245248
}
246249

247-
const ForwardedWithStyles = React.forwardRef((props, ref) => (
248-
<WithStyles {...props} forwardedRef={ref} />
249-
));
250+
// TODO: remove conditional once breaking change to only support React 16.3+
251+
// ref: https://github.com/airbnb/react-with-styles/pull/240#discussion_r533497857
252+
if (typeof React.forwardRef !== 'undefined') {
253+
WithStyles.propTypes = {
254+
forwardedRef: ref(),
255+
};
256+
}
257+
258+
// TODO: remove conditional once breaking change to only support React 16.3+
259+
// ref: https://github.com/airbnb/react-with-styles/pull/240#discussion_r533497857
260+
const ForwardedWithStyles = typeof React.forwardRef === 'undefined'
261+
? WithStyles
262+
: React.forwardRef((props, forwardedRef) => (
263+
<WithStyles {...props} forwardedRef={forwardedRef} />
264+
));
250265

251266
// Copy the wrapped component's prop types and default props on WithStyles
252267
if (WrappedComponent.propTypes) {

0 commit comments

Comments
 (0)