Skip to content

Commit

Permalink
Fix to add warning when non-strings are given as children
Browse files Browse the repository at this point in the history
  • Loading branch information
wooorm committed May 6, 2021
1 parent 592599f commit 5cf6e1b
Show file tree
Hide file tree
Showing 2 changed files with 46 additions and 1 deletion.
14 changes: 13 additions & 1 deletion src/react-markdown.js
Original file line number Diff line number Diff line change
Expand Up @@ -98,9 +98,21 @@ function ReactMarkdown(options) {
.use(options.rehypePlugins || [])
.use(filter, options)

let children = options.children

if (typeof children !== 'string') {
if (children !== undefined && children !== null) {
console.warn(
`[react-markdown] Warning: please pass a string as \`children\` (not: \`${children}\`)`
)
}

children = ''
}

/** @type {Root} */
// @ts-ignore we’ll throw if it isn’t a root next.
const hastNode = processor.runSync(processor.parse(options.children || ''))
const hastNode = processor.runSync(processor.parse(children))

if (hastNode.type !== 'root') {
throw new TypeError('Expected a `root` node')
Expand Down
33 changes: 33 additions & 0 deletions test/react-markdown.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,39 @@ test('should warn when passed `source`', () => {
console.warn = warn
})

test('should warn when passed non-string children (number)', () => {
const {error, warn} = console
console.error = jest.fn()
console.warn = jest.fn()
// @ts-ignore runtime
expect(renderHTML(<Markdown children={1} />)).toEqual('')
expect(console.warn).toHaveBeenCalledWith(
'[react-markdown] Warning: please pass a string as `children` (not: `1`)'
)
console.error = error
console.warn = warn
})

test('should warn when passed non-string children (boolean)', () => {
const {error, warn} = console
console.error = jest.fn()
console.warn = jest.fn()
// @ts-ignore runtime
expect(renderHTML(<Markdown children={false} />)).toEqual('')
expect(console.warn).toHaveBeenCalledWith(
'[react-markdown] Warning: please pass a string as `children` (not: `false`)'
)
console.error = error
console.warn = warn
})

test('should not warn when passed `null` as children', () => {
expect(renderHTML(<Markdown children={null} />)).toEqual('')
})
test('should not warn when passed `undefined` as children', () => {
expect(renderHTML(<Markdown children={undefined} />)).toEqual('')
})

test('should warn when passed `allowDangerousHtml`', () => {
const warn = console.warn
console.warn = jest.fn()
Expand Down

0 comments on commit 5cf6e1b

Please sign in to comment.