Skip to content

Commit 5cf6e1b

Browse files
committed
Fix to add warning when non-strings are given as children
1 parent 592599f commit 5cf6e1b

File tree

2 files changed

+46
-1
lines changed

2 files changed

+46
-1
lines changed

src/react-markdown.js

+13-1
Original file line numberDiff line numberDiff line change
@@ -98,9 +98,21 @@ function ReactMarkdown(options) {
9898
.use(options.rehypePlugins || [])
9999
.use(filter, options)
100100

101+
let children = options.children
102+
103+
if (typeof children !== 'string') {
104+
if (children !== undefined && children !== null) {
105+
console.warn(
106+
`[react-markdown] Warning: please pass a string as \`children\` (not: \`${children}\`)`
107+
)
108+
}
109+
110+
children = ''
111+
}
112+
101113
/** @type {Root} */
102114
// @ts-ignore we’ll throw if it isn’t a root next.
103-
const hastNode = processor.runSync(processor.parse(options.children || ''))
115+
const hastNode = processor.runSync(processor.parse(children))
104116

105117
if (hastNode.type !== 'root') {
106118
throw new TypeError('Expected a `root` node')

test/react-markdown.test.js

+33
Original file line numberDiff line numberDiff line change
@@ -44,6 +44,39 @@ test('should warn when passed `source`', () => {
4444
console.warn = warn
4545
})
4646

47+
test('should warn when passed non-string children (number)', () => {
48+
const {error, warn} = console
49+
console.error = jest.fn()
50+
console.warn = jest.fn()
51+
// @ts-ignore runtime
52+
expect(renderHTML(<Markdown children={1} />)).toEqual('')
53+
expect(console.warn).toHaveBeenCalledWith(
54+
'[react-markdown] Warning: please pass a string as `children` (not: `1`)'
55+
)
56+
console.error = error
57+
console.warn = warn
58+
})
59+
60+
test('should warn when passed non-string children (boolean)', () => {
61+
const {error, warn} = console
62+
console.error = jest.fn()
63+
console.warn = jest.fn()
64+
// @ts-ignore runtime
65+
expect(renderHTML(<Markdown children={false} />)).toEqual('')
66+
expect(console.warn).toHaveBeenCalledWith(
67+
'[react-markdown] Warning: please pass a string as `children` (not: `false`)'
68+
)
69+
console.error = error
70+
console.warn = warn
71+
})
72+
73+
test('should not warn when passed `null` as children', () => {
74+
expect(renderHTML(<Markdown children={null} />)).toEqual('')
75+
})
76+
test('should not warn when passed `undefined` as children', () => {
77+
expect(renderHTML(<Markdown children={undefined} />)).toEqual('')
78+
})
79+
4780
test('should warn when passed `allowDangerousHtml`', () => {
4881
const warn = console.warn
4982
console.warn = jest.fn()

0 commit comments

Comments
 (0)