Skip to content

Commit

Permalink
feat: honor displayName of context types
Browse files Browse the repository at this point in the history
  • Loading branch information
eps1lon committed Feb 13, 2020
1 parent 24b5fd0 commit 21a87a4
Show file tree
Hide file tree
Showing 3 changed files with 14 additions and 4 deletions.
5 changes: 5 additions & 0 deletions packages/react/src/ReactContext.js
Original file line number Diff line number Diff line change
Expand Up @@ -120,6 +120,11 @@ export function createContext<T>(
return context.Consumer;
},
},
displayName: {
get() {
return context.displayName;
},
},
});
// $FlowFixMe: Flow complains about missing properties because it doesn't understand defineProperty
context.Consumer = Consumer;
Expand Down
4 changes: 2 additions & 2 deletions packages/react/src/__tests__/ReactContext-test.js
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ describe('ReactContext', () => {
Scheduler = require('scheduler');
});

it('should ignore a displayName if set on the context type', () => {
it('should honor a displayName if set on the context type', () => {
spyOnDevAndProd(console, 'error');
const Context = React.createContext(null);
Context.displayName = 'MyContextType';
Expand All @@ -39,7 +39,7 @@ describe('ReactContext', () => {
expect(Scheduler).toFlushAndThrow('consumer error');
expect(console.error.calls.count()).toEqual(3);
expect(console.error.calls.argsFor(2)[0]).toMatch(
'The above error occurred in the <Context.Consumer>',
'The above error occurred in the <MyContextType.Consumer>',
);
});
});
9 changes: 7 additions & 2 deletions packages/shared/getComponentName.js
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@ import {
REACT_CHUNK_TYPE,
} from 'shared/ReactSymbols';
import {refineResolvedLazyComponent} from 'shared/ReactLazyComponent';
import type {ReactContext} from 'shared/ReactTypes';

function getWrappedName(
outerType: mixed,
Expand All @@ -37,6 +38,10 @@ function getWrappedName(
);
}

function getContextName(type: ReactContext<any>) {
return type.displayName || 'Context';
}

function getComponentName(type: mixed): string | null {
if (type == null) {
// Host root, text node or just invalid type.
Expand Down Expand Up @@ -73,9 +78,9 @@ function getComponentName(type: mixed): string | null {
if (typeof type === 'object') {
switch (type.$$typeof) {
case REACT_CONTEXT_TYPE:
return 'Context.Consumer';
return getContextName(type) + '.Consumer';
case REACT_PROVIDER_TYPE:
return 'Context.Provider';
return getContextName(type._context) + '.Provider';
case REACT_FORWARD_REF_TYPE:
return getWrappedName(type, type.render, 'ForwardRef');
case REACT_MEMO_TYPE:
Expand Down

0 comments on commit 21a87a4

Please sign in to comment.