Skip to content

Commit

Permalink
[withStyles] Conditionally forward ref to inner component
Browse files Browse the repository at this point in the history
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)
  • Loading branch information
Austin Wood committed Apr 6, 2021
1 parent fdff766 commit 220e2f0
Showing 1 changed file with 20 additions and 5 deletions.
25 changes: 20 additions & 5 deletions src/withStyles.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
import React from 'react';
import hoistNonReactStatics from 'hoist-non-react-statics';
import getComponentName from 'airbnb-prop-types/build/helpers/getComponentName';
import ref from 'airbnb-prop-types/build/ref';

import EMPTY_STYLES_FN from './utils/emptyStylesFn';
import withPerf from './utils/perf';
Expand Down Expand Up @@ -232,8 +233,10 @@ export function withStyles(

return (
<WrappedComponent
ref={forwardedRef}
{...rest}
// TODO: remove conditional once breaking change to only support React 16.3+
// ref: https://github.com/airbnb/react-with-styles/pull/240#discussion_r533497857
ref={typeof React.forwardRef === 'undefined' ? undefined : forwardedRef}
{...(typeof React.forwardRef === 'undefined' ? this.props : rest)}
{...{
[themePropName]: theme,
[stylesPropName]: styles,
Expand All @@ -244,9 +247,21 @@ export function withStyles(
}
}

const ForwardedWithStyles = React.forwardRef((props, ref) => (
<WithStyles {...props} forwardedRef={ref} />
));
// TODO: remove conditional once breaking change to only support React 16.3+
// ref: https://github.com/airbnb/react-with-styles/pull/240#discussion_r533497857
if (typeof React.forwardRef !== 'undefined') {
WithStyles.propTypes = {
forwardedRef: ref(),
};
}

// TODO: remove conditional once breaking change to only support React 16.3+
// ref: https://github.com/airbnb/react-with-styles/pull/240#discussion_r533497857
const ForwardedWithStyles = typeof React.forwardRef === 'undefined'
? WithStyles
: React.forwardRef((props, forwardedRef) => (
<WithStyles {...props} forwardedRef={forwardedRef} />
));

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

0 comments on commit 220e2f0

Please sign in to comment.