@samitouri / QOS-React / commits / 095dd5049c

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

* Add DEV warning if forwardRef function doesn't use the ref param * Fixed a forwardRef arity warning in another test

Brian Vaughn committed Jul 7, 2018 at 08:11 UTC 095dd5049c7810841024078f4bbea7e4d7766acc
3 files changed +34 -8
packages/react-test-renderer/src/__tests__/ReactTestRendererTraversal-test.js
+1 -1
@@ -201,7 +201,7 @@ describe('ReactTestRendererTraversal', () => {
201 });
202
203 it('can have special nodes as roots', () => {
204 - const FR = React.forwardRef(props => <section {...props} />);
204 + const FR = React.forwardRef((props, ref) => <section {...props} />);
205 expect(
206 ReactTestRenderer.create(
207 <FR>
packages/react/src/__tests__/forwardRef-test.js
+20 -2
@@ -136,12 +136,12 @@ describe('forwardRef', () => {
136 });
137
138 it('should warn if the render function provided has propTypes or defaultProps attributes', () => {
139 - function renderWithPropTypes() {
139 + function renderWithPropTypes(props, ref) {
140 return null;
141 }
142 renderWithPropTypes.propTypes = {};
143
144 - function renderWithDefaultProps() {
144 + function renderWithDefaultProps(props, ref) {
145 return null;
146 }
147 renderWithDefaultProps.defaultProps = {};
@@ -155,4 +155,22 @@ describe('forwardRef', () => {
155 'Did you accidentally pass a React component?',
156 );
157 });
158 +
159 + it('should warn if the render function provided does not use the forwarded ref parameter', () => {
160 + function arityOfZero() {
161 + return null;
162 + }
163 +
164 + const arityOfOne = props => null;
165 +
166 + expect(() => React.forwardRef(arityOfZero)).toWarnDev(
167 + 'forwardRef render functions accept two parameters: props and ref. ' +
168 + 'Did you forget to use the ref parameter?',
169 + );
170 +
171 + expect(() => React.forwardRef(arityOfOne)).toWarnDev(
172 + 'forwardRef render functions accept two parameters: props and ref. ' +
173 + 'Did you forget to use the ref parameter?',
174 + );
175 + });
176 });
packages/react/src/forwardRef.js
+13 -5
@@ -13,11 +13,19 @@ export default function forwardRef<Props, ElementType: React$ElementType>(
13 render: (props: Props, ref: React$ElementRef<ElementType>) => React$Node,
14 ) {
15 if (__DEV__) {
16 - warning(
17 - typeof render === 'function',
18 - 'forwardRef requires a render function but was given %s.',
19 - render === null ? 'null' : typeof render,
20 - );
16 + if (typeof render !== 'function') {
17 + warning(
18 + false,
19 + 'forwardRef requires a render function but was given %s.',
20 + render === null ? 'null' : typeof render,
21 + );
22 + } else {
23 + warning(
24 + render.length === 2,
25 + 'forwardRef render functions accept two parameters: props and ref. ' +
26 + 'Did you forget to use the ref parameter?',
27 + );
28 + }
29
30 if (render != null) {
31 warning(