fix(react): support void children in experimentalReactChildren (#8455)

This commit is contained in:
Nate Moore 2023-09-07 15:54:39 -05:00 committed by GitHub
parent 5c23bf1c90
commit 85fe213fe0
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
2 changed files with 14 additions and 11 deletions

View file

@ -0,0 +1,5 @@
---
'@astrojs/react': patch
---
Update `experimentalReactChildren` behavior to support void tags

View file

@ -1,9 +1,12 @@
import { parse, walkSync, DOCUMENT_NODE, ELEMENT_NODE, TEXT_NODE } from 'ultrahtml';
import { createElement, Fragment } from 'react';
let ids = 0;
export default function convert(children) {
const nodeMap = new WeakMap();
let doc = parse(children.toString().trim());
let id = ids++;
let key = 0;
let root = createElement(Fragment, { children: [] });
walkSync(doc, (node, parent, index) => {
@ -12,23 +15,18 @@ export default function convert(children) {
nodeMap.set(node, root);
} else if (node.type === ELEMENT_NODE) {
const { class: className, ...props } = node.attributes;
newNode = createElement(node.name, { ...props, className, children: [] });
// NOTE: do not manually pass `children`, React handles this internally
newNode = createElement(node.name, { ...props, className, key: `${id}-${key++}` });
nodeMap.set(node, newNode);
if (parent) {
const newParent = nodeMap.get(parent);
newParent.props.children[index] = newNode;
}
} else if (node.type === TEXT_NODE) {
newNode = node.value.trim();
if (newNode.trim()) {
if (parent) {
const newParent = nodeMap.get(parent);
if (parent.children.length === 1) {
newParent.props.children[0] = newNode;
} else {
newParent.props.children[index] = newNode;
}
}
newNode = node.value;
if (newNode.trim() && parent) {
const newParent = nodeMap.get(parent);
newParent.props.children[index] = newNode;
}
}
});