From cc05806ed5d0832661f9c158e22d64b0bbd816c1 Mon Sep 17 00:00:00 2001 From: Titus Wormer Date: Thu, 2 Feb 2023 19:54:42 +0100 Subject: [PATCH] Fix to not pass children for void elements React warns when `children: []` is passed for a void element, such as `hr` or `br`. To solve that, we can pass `children: undefined` instead. --- lib/index.js | 14 +++++++------- test/index.js | 6 ++++++ 2 files changed, 13 insertions(+), 7 deletions(-) diff --git a/lib/index.js b/lib/index.js index 5440f53..f95ecfb 100644 --- a/lib/index.js +++ b/lib/index.js @@ -67,7 +67,7 @@ * @typedef {JSX.Element | string | null | undefined} Child * Child. * - * @typedef {{children: Array, node?: Element | undefined, [prop: string]: Value | Element | undefined | Array}} Props + * @typedef {{children: Array | undefined, node?: Element | undefined, [prop: string]: Value | Element | undefined | Array}} Props * Properties and children. * * @callback Create @@ -260,7 +260,7 @@ export function toJsxRuntime(tree, options) { return state.create( tree, state.Fragment, - {children: result ? [result] : []}, + {children: result ? [result] : undefined}, undefined ) } @@ -296,7 +296,7 @@ function one(state, node, key) { let type = state.Fragment if (node.type === 'element') { - if (tableElements.has(node.tagName)) { + if (children && tableElements.has(node.tagName)) { children = children.filter((child) => !whitespace(child)) } @@ -340,7 +340,7 @@ function productionCreate(_, jsx, jsxs) { return create /** @type {Create} */ function create(_, type, props, key) { - const isStaticChildren = props.children.length > 1 + const isStaticChildren = props.children ? props.children.length > 1 : false const fn = isStaticChildren ? jsxs : jsx return fn(type, props, key) } @@ -358,7 +358,7 @@ function developmentCreate(filePath, jsxDEV) { return create /** @type {Create} */ function create(node, type, props, key) { - const isStaticChildren = props.children.length > 1 + const isStaticChildren = props.children ? props.children.length > 1 : false const point = pointStart(node) return jsxDEV( type, @@ -382,7 +382,7 @@ function developmentCreate(filePath, jsxDEV) { * Info passed around. * @param {Parent} node * Current element. - * @returns {Array} + * @returns {Array | undefined} * Children. */ function createChildren(state, node) { @@ -407,7 +407,7 @@ function createChildren(state, node) { if (result !== undefined) children.push(result) } - return children + return children.length > 0 ? children : undefined } /** diff --git a/test/index.js b/test/index.js index e98a7cc..d0dd858 100644 --- a/test/index.js +++ b/test/index.js @@ -292,6 +292,12 @@ test('children', () => { '
', 'should support svg in html' ) + + assert.equal( + renderToStaticMarkup(toJsxRuntime(h('hr'), production)), + '
', + 'should support a void element' + ) }) test('source', () => {