Skip to content

Commit 9ea4bc6

Browse files
authored
Fix false positive context warning when using an old React (#13850)
1 parent 4773fdf commit 9ea4bc6

File tree

2 files changed

+34
-7
lines changed

2 files changed

+34
-7
lines changed

packages/react-reconciler/src/ReactFiberBeginWork.js

+12-7
Original file line numberDiff line numberDiff line change
@@ -1118,13 +1118,18 @@ function updateContextConsumer(
11181118
// in DEV mode if this property exists or not and warn if it does not.
11191119
if (__DEV__) {
11201120
if ((context: any)._context === undefined) {
1121-
if (!hasWarnedAboutUsingContextAsConsumer) {
1122-
hasWarnedAboutUsingContextAsConsumer = true;
1123-
warning(
1124-
false,
1125-
'Rendering <Context> directly is not supported and will be removed in ' +
1126-
'a future major release. Did you mean to render <Context.Consumer> instead?',
1127-
);
1121+
// This may be because it's a Context (rather than a Consumer).
1122+
// Or it may be because it's older React where they're the same thing.
1123+
// We only want to warn if we're sure it's a new React.
1124+
if (context !== context.Consumer) {
1125+
if (!hasWarnedAboutUsingContextAsConsumer) {
1126+
hasWarnedAboutUsingContextAsConsumer = true;
1127+
warning(
1128+
false,
1129+
'Rendering <Context> directly is not supported and will be removed in ' +
1130+
'a future major release. Did you mean to render <Context.Consumer> instead?',
1131+
);
1132+
}
11281133
}
11291134
} else {
11301135
context = (context: any)._context;

packages/react-reconciler/src/__tests__/ReactNewContext-test.internal.js

+22
Original file line numberDiff line numberDiff line change
@@ -1584,6 +1584,28 @@ Context fuzz tester error! Copy and paste the following line into the test suite
15841584
);
15851585
});
15861586

1587+
// False positive regression test.
1588+
it('should not warn when using Consumer from React < 16.6 with newer renderer', () => {
1589+
const BarContext = React.createContext({value: 'bar-initial'});
1590+
// React 16.5 and earlier didn't have a separate object.
1591+
BarContext.Consumer = BarContext;
1592+
1593+
function Component() {
1594+
return (
1595+
<React.Fragment>
1596+
<BarContext.Provider value={{value: 'bar-updated'}}>
1597+
<BarContext.Consumer>
1598+
{({value}) => <div actual={value} expected="bar-updated" />}
1599+
</BarContext.Consumer>
1600+
</BarContext.Provider>
1601+
</React.Fragment>
1602+
);
1603+
}
1604+
1605+
ReactNoop.render(<Component />);
1606+
ReactNoop.flush();
1607+
});
1608+
15871609
it('should warn with an error message when using nested context consumers in DEV', () => {
15881610
const BarContext = React.createContext({value: 'bar-initial'});
15891611
const BarConsumer = BarContext;

0 commit comments

Comments
 (0)