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 { parse, walkSync, DOCUMENT_NODE, ELEMENT_NODE, TEXT_NODE } from 'ultrahtml';
import { createElement, Fragment } from 'react'; import { createElement, Fragment } from 'react';
let ids = 0;
export default function convert(children) { export default function convert(children) {
const nodeMap = new WeakMap(); const nodeMap = new WeakMap();
let doc = parse(children.toString().trim()); let doc = parse(children.toString().trim());
let id = ids++;
let key = 0;
let root = createElement(Fragment, { children: [] }); let root = createElement(Fragment, { children: [] });
walkSync(doc, (node, parent, index) => { walkSync(doc, (node, parent, index) => {
@ -12,25 +15,20 @@ export default function convert(children) {
nodeMap.set(node, root); nodeMap.set(node, root);
} else if (node.type === ELEMENT_NODE) { } else if (node.type === ELEMENT_NODE) {
const { class: className, ...props } = node.attributes; 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); nodeMap.set(node, newNode);
if (parent) { if (parent) {
const newParent = nodeMap.get(parent); const newParent = nodeMap.get(parent);
newParent.props.children[index] = newNode; newParent.props.children[index] = newNode;
} }
} else if (node.type === TEXT_NODE) { } else if (node.type === TEXT_NODE) {
newNode = node.value.trim(); newNode = node.value;
if (newNode.trim()) { if (newNode.trim() && parent) {
if (parent) {
const newParent = nodeMap.get(parent); const newParent = nodeMap.get(parent);
if (parent.children.length === 1) {
newParent.props.children[0] = newNode;
} else {
newParent.props.children[index] = newNode; newParent.props.children[index] = newNode;
} }
} }
}
}
}); });
return root.props.children; return root.props.children;