Skip to content

Commit

Permalink
fix(react): support void children in experimentalReactChildren (#8455)
Browse files Browse the repository at this point in the history
  • Loading branch information
natemoo-re authored Sep 7, 2023
1 parent 5c23bf1 commit 85fe213
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 11 deletions.
5 changes: 5 additions & 0 deletions .changeset/cool-jokes-unite.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'@astrojs/react': patch
---

Update `experimentalReactChildren` behavior to support void tags
20 changes: 9 additions & 11 deletions packages/integrations/react/vnode-children.js
Original file line number Diff line number Diff line change
@@ -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) => {
Expand All @@ -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;
}
}
});
Expand Down

0 comments on commit 85fe213

Please sign in to comment.