Skip to content

Commit

Permalink
Merge pull request #301 from preactjs/comments
Browse files Browse the repository at this point in the history
  • Loading branch information
marvinhagemeister authored Jun 9, 2023
2 parents 52be312 + 8e0a6e3 commit e68d93c
Show file tree
Hide file tree
Showing 3 changed files with 29 additions and 0 deletions.
5 changes: 5 additions & 0 deletions .changeset/shy-hotels-impress.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'preact-render-to-string': minor
---

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.
6 changes: 6 additions & 0 deletions src/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -165,6 +165,12 @@ function _renderToString(vnode, context, isSvgMode, selectValue, parent) {
// Invoke rendering on Components
if (typeof type === 'function') {
if (type === Fragment) {
// Fragments are the least used components of core that's why
// branching here for comments has the least effect on perf.
if (props.UNSTABLE_comment) {
return '<!--' + encodeEntities(props.UNSTABLE_comment || '') + '-->';
}

rendered = props.children;
} else {
contextType = type.contextType;
Expand Down
18 changes: 18 additions & 0 deletions test/render.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -1309,6 +1309,24 @@ describe('render', () => {
expect(render(<div>{() => {}}</div>)).to.equal('<div></div>');
});

describe('HTML Comments', () => {
it('should render HTML comments via Fragments', () => {
expect(render(<Fragment UNSTABLE_comment="foo" />)).to.equal(
'<!--foo-->'
);
});

it('should ignore children with comment prop', () => {
expect(
render(
<Fragment UNSTABLE_comment="foo">
<p>foo</p>
</Fragment>
)
).to.equal('<!--foo-->');
});
});

describe('vnode masks (useId)', () => {
it('should skip component top level Fragment child', () => {
const Wrapper = ({ children }) => <Fragment>{children}</Fragment>;
Expand Down

0 comments on commit e68d93c

Please sign in to comment.