Skip to content

Commit 375f320

Browse files
committed
Do not pass ref to functional components w/out forwardRef
If we can't use forwardRef, we shouldn't ever pass a ref to a functional component. Use innerRef workaround instead. Fixes #6934
1 parent 55695fa commit 375f320

File tree

2 files changed

+33
-16
lines changed

2 files changed

+33
-16
lines changed

packages/react-router-dom/modules/Link.js

Lines changed: 14 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -5,9 +5,10 @@ import invariant from "tiny-invariant";
55
import { resolveToLocation, normalizeToLocation } from "./utils/locationUtils";
66

77
// React 15 compat
8+
const forwardRefShim = C => C;
89
let { forwardRef } = React;
910
if (typeof forwardRef === "undefined") {
10-
forwardRef = C => C;
11+
forwardRef = forwardRefShim;
1112
}
1213

1314
function isModifiedEvent(event) {
@@ -70,18 +71,26 @@ const Link = forwardRef(
7071
);
7172

7273
const href = location ? history.createHref(location) : "";
73-
74-
return React.createElement(component, {
74+
const props = {
7575
...rest,
76-
ref: forwardedRef || innerRef,
7776
href,
7877
navigate() {
7978
const location = resolveToLocation(to, context.location);
8079
const method = replace ? history.replace : history.push;
8180

8281
method(location);
8382
}
84-
});
83+
};
84+
85+
// React 15 compat
86+
if (forwardRefShim !== forwardRef) {
87+
props.ref = forwardedRef || innerRef;
88+
} else {
89+
// TODO: deprecate
90+
props.innerRef = innerRef;
91+
}
92+
93+
return React.createElement(component, props);
8594
}}
8695
</RouterContext.Consumer>
8796
);

packages/react-router-dom/modules/NavLink.js

Lines changed: 19 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -6,9 +6,10 @@ import Link from "./Link";
66
import { resolveToLocation, normalizeToLocation } from "./utils/locationUtils";
77

88
// React 15 compat
9+
const forwardRefShim = C => C;
910
let { forwardRef } = React;
1011
if (typeof forwardRef === "undefined") {
11-
forwardRef = C => C;
12+
forwardRef = forwardRefShim;
1213
}
1314

1415
function joinClassnames(...classnames) {
@@ -67,16 +68,23 @@ const NavLink = forwardRef(
6768
: classNameProp;
6869
const style = isActive ? { ...styleProp, ...activeStyle } : styleProp;
6970

70-
return (
71-
<Link
72-
ref={forwardedRef || innerRef}
73-
aria-current={(isActive && ariaCurrent) || null}
74-
className={className}
75-
style={style}
76-
to={toLocation}
77-
{...rest}
78-
/>
79-
);
71+
const props = {
72+
"aria-current": (isActive && ariaCurrent) || null,
73+
className,
74+
style,
75+
to: toLocation,
76+
...rest
77+
};
78+
79+
// React 15 compat
80+
if (forwardRefShim !== forwardRef) {
81+
props.ref = forwardedRef || innerRef;
82+
} else {
83+
// TODO: deprecate
84+
props.innerRef = innerRef;
85+
}
86+
87+
return <Link {...props} />;
8088
}}
8189
</RouterContext.Consumer>
8290
);

0 commit comments

Comments
 (0)