Skip to content

Commit e68d93c

Browse files
Merge pull request #301 from preactjs/comments
2 parents 52be312 + 8e0a6e3 commit e68d93c

File tree

3 files changed

+29
-0
lines changed

3 files changed

+29
-0
lines changed

.changeset/shy-hotels-impress.md

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
---
2+
'preact-render-to-string': minor
3+
---
4+
5+
Add experimental ability to render HTML comments via `<Fragment UNSTABLE_comment="my-comment" />`. When the `UNSTABLE_comment` prop is present all children of that `Fragment` will be ignored and a HTML comment will be rendered instead. This feature is added to allow framework authors to experiment with marking DOM for hydration in the client. Note that it's marked as unstable and might change in the future.

src/index.js

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -165,6 +165,12 @@ function _renderToString(vnode, context, isSvgMode, selectValue, parent) {
165165
// Invoke rendering on Components
166166
if (typeof type === 'function') {
167167
if (type === Fragment) {
168+
// Fragments are the least used components of core that's why
169+
// branching here for comments has the least effect on perf.
170+
if (props.UNSTABLE_comment) {
171+
return '<!--' + encodeEntities(props.UNSTABLE_comment || '') + '-->';
172+
}
173+
168174
rendered = props.children;
169175
} else {
170176
contextType = type.contextType;

test/render.test.js

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1309,6 +1309,24 @@ describe('render', () => {
13091309
expect(render(<div>{() => {}}</div>)).to.equal('<div></div>');
13101310
});
13111311

1312+
describe('HTML Comments', () => {
1313+
it('should render HTML comments via Fragments', () => {
1314+
expect(render(<Fragment UNSTABLE_comment="foo" />)).to.equal(
1315+
'<!--foo-->'
1316+
);
1317+
});
1318+
1319+
it('should ignore children with comment prop', () => {
1320+
expect(
1321+
render(
1322+
<Fragment UNSTABLE_comment="foo">
1323+
<p>foo</p>
1324+
</Fragment>
1325+
)
1326+
).to.equal('<!--foo-->');
1327+
});
1328+
});
1329+
13121330
describe('vnode masks (useId)', () => {
13131331
it('should skip component top level Fragment child', () => {
13141332
const Wrapper = ({ children }) => <Fragment>{children}</Fragment>;

0 commit comments

Comments
 (0)