Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add DEV warning if forwardRef function doesn't use the ref param #13168

Merged
merged 2 commits into from Jul 7, 2018
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
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
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
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