diff --git a/.changeset/brave-ticks-save.md b/.changeset/brave-ticks-save.md new file mode 100644 index 00000000000..28f6cbf09d3 --- /dev/null +++ b/.changeset/brave-ticks-save.md @@ -0,0 +1,8 @@ +--- +'react-docgen': patch +--- + +Fix `defaultPropsHandler` dropping default values that are template literals, +both in destructured parameters and in `defaultProps`. They are now reported +with their source text as the value and `computed: false` +([#1203](https://github.com/reactjs/react-docgen/issues/1203)). diff --git a/packages/react-docgen/src/handlers/__tests__/defaultPropsHandler-test.ts b/packages/react-docgen/src/handlers/__tests__/defaultPropsHandler-test.ts index 5675a16494e..97eb2d36fed 100644 --- a/packages/react-docgen/src/handlers/__tests__/defaultPropsHandler-test.ts +++ b/packages/react-docgen/src/handlers/__tests__/defaultPropsHandler-test.ts @@ -7,7 +7,7 @@ import type { ObjectExpression, VariableDeclaration, } from '@babel/types'; -import { parse, makeMockImporter } from '../../../tests/utils'; +import { parse, parseTypescript, makeMockImporter } from '../../../tests/utils'; import DocumentationBuilder from '../../Documentation'; import type DocumentationMock from '../../__mocks__/Documentation'; import defaultPropsHandler from '../defaultPropsHandler.js'; @@ -699,4 +699,112 @@ describe('defaultPropsHandler', () => { expect(documentation.descriptors).toMatchSnapshot(); }); }); + + describe('template literals', () => { + test('finds template literal defaults in destructured params', () => { + const src = ` + function A({ a = 1, tpl = \`Save\` }) { + return
; + } + `; + + defaultPropsHandler(documentation, parse.statement(src)); + expect(documentation.descriptors).toEqual({ + a: { defaultValue: { value: '1', computed: false } }, + tpl: { defaultValue: { value: '`Save`', computed: false } }, + }); + }); + + test('finds template literal defaults for typed props', () => { + const src = ` + type Props = { tpl?: string; n?: number }; + function A({ tpl = \`Save\`, n = 1 }: Props) { + return null; + } + `; + + defaultPropsHandler(documentation, parseTypescript.statementLast(src)); + expect(documentation.descriptors).toEqual({ + tpl: { defaultValue: { value: '`Save`', computed: false } }, + n: { defaultValue: { value: '1', computed: false } }, + }); + }); + + test('finds template literal defaults in class defaultProps', () => { + const src = ` + class Foo { + static defaultProps = { + tpl: \`Save\`, + }; + } + `; + + defaultPropsHandler( + documentation, + parse.statement