Skip to content

Commit

Permalink
Add DEV warning if forwardRef function doesn't use the ref param (#13168
Browse files Browse the repository at this point in the history
)

* Add DEV warning if forwardRef function doesn't use the ref param
* Fixed a forwardRef arity warning in another test
  • Loading branch information
bvaughn authored Jul 7, 2018
1 parent 5662595 commit 095dd50
Show file tree
Hide file tree
Showing 3 changed files with 34 additions and 8 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -201,7 +201,7 @@ describe('ReactTestRendererTraversal', () => {
});

it('can have special nodes as roots', () => {
const FR = React.forwardRef(props => <section {...props} />);
const FR = React.forwardRef((props, ref) => <section {...props} />);
expect(
ReactTestRenderer.create(
<FR>
Expand Down
22 changes: 20 additions & 2 deletions packages/react/src/__tests__/forwardRef-test.js
Original file line number Diff line number Diff line change
Expand Up @@ -136,12 +136,12 @@ describe('forwardRef', () => {
});

it('should warn if the render function provided has propTypes or defaultProps attributes', () => {
function renderWithPropTypes() {
function renderWithPropTypes(props, ref) {
return null;
}
renderWithPropTypes.propTypes = {};

function renderWithDefaultProps() {
function renderWithDefaultProps(props, ref) {
return null;
}
renderWithDefaultProps.defaultProps = {};
Expand All @@ -155,4 +155,22 @@ describe('forwardRef', () => {
'Did you accidentally pass a React component?',
);
});

it('should warn if the render function provided does not use the forwarded ref parameter', () => {
function arityOfZero() {
return null;
}

const arityOfOne = props => null;

expect(() => React.forwardRef(arityOfZero)).toWarnDev(
'forwardRef render functions accept two parameters: props and ref. ' +
'Did you forget to use the ref parameter?',
);

expect(() => React.forwardRef(arityOfOne)).toWarnDev(
'forwardRef render functions accept two parameters: props and ref. ' +
'Did you forget to use the ref parameter?',
);
});
});
18 changes: 13 additions & 5 deletions packages/react/src/forwardRef.js
Original file line number Diff line number Diff line change
Expand Up @@ -13,11 +13,19 @@ export default function forwardRef<Props, ElementType: React$ElementType>(
render: (props: Props, ref: React$ElementRef<ElementType>) => React$Node,
) {
if (__DEV__) {
warning(
typeof render === 'function',
'forwardRef requires a render function but was given %s.',
render === null ? 'null' : typeof render,
);
if (typeof render !== 'function') {
warning(
false,
'forwardRef requires a render function but was given %s.',
render === null ? 'null' : typeof render,
);
} else {
warning(
render.length === 2,
'forwardRef render functions accept two parameters: props and ref. ' +
'Did you forget to use the ref parameter?',
);
}

if (render != null) {
warning(
Expand Down

0 comments on commit 095dd50

Please sign in to comment.