Skip to content

Commit

Permalink
improve displayName/name handling
Browse files Browse the repository at this point in the history
  • Loading branch information
urugator committed Feb 11, 2023
1 parent 9e09fab commit f239cb4
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 10 deletions.
11 changes: 7 additions & 4 deletions packages/mobx-react-lite/__tests__/observer.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -618,12 +618,15 @@ it("should hoist known statics only", () => {
expect(wrapped.render).toBe(undefined)
})

it("should have the correct displayName", () => {
const TestComponent = observer(function MyComponent() {
it("should inherit original name/displayName #3438", () => {
function Name() {
return null
})
}
Name.displayName = "DisplayName"
const TestComponent = observer(Name)

expect((TestComponent as any).type.displayName).toBe("MyComponent")
expect((TestComponent as any).type.name).toBe("Name")
expect((TestComponent as any).type.displayName).toBe("DisplayName")
})

test("parent / childs render in the right order", done => {
Expand Down
14 changes: 8 additions & 6 deletions packages/mobx-react-lite/src/observer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -104,11 +104,13 @@ export function observer<P extends object, TRef = {}>(
return useObserver(() => render(props, ref), baseComponentName)
}

// Don't set `displayName` for anonymous components,
// so the `displayName` can be customized by user, see #3192.
if (baseComponentName !== "") {
;(observerComponent as React.FunctionComponent).displayName = baseComponentName
}
// Inherit original name and displayName, see #3438
;(observerComponent as React.FunctionComponent).displayName = baseComponent.displayName
Object.defineProperty(observerComponent, "name", {
value: baseComponent.name,
writable: true,
configurable: true
})

// Support legacy context: `contextTypes` must be applied before `memo`
if ((baseComponent as any).contextTypes) {
Expand Down Expand Up @@ -136,7 +138,7 @@ export function observer<P extends object, TRef = {}>(
set() {
throw new Error(
`[mobx-react-lite] \`${
this.displayName || this.type?.displayName || "Component"
this.displayName || this.type?.displayName || this.type?.name || "Component"
}.contextTypes\` must be set before applying \`observer\`.`
)
}
Expand Down

0 comments on commit f239cb4

Please sign in to comment.