Skip to content

Commit

Permalink
Add support for rendering HTML comments
Browse files Browse the repository at this point in the history
This is done via Fragments because they are the least common components.
That way the additional branching has minimal impact
  • Loading branch information
marvinhagemeister committed Jun 7, 2023
1 parent 52be312 commit 659b456
Show file tree
Hide file tree
Showing 3 changed files with 29 additions and 0 deletions.
7 changes: 7 additions & 0 deletions .changeset/shy-hotels-impress.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
---
'preact-render-to-string': minor
---

Add ability to render comments via `<Fragment comment="my-comment" />`. When the `comment` prop is present all children of that `Fragment` will be ignored. This PR only supports that in server environments as it's useful to mark islands and other things. It's not supported in the browser.

We picked a `Fragment` for this as it's the least common component and therefore the branch in our code with the least impact on perf by adding another if-check.
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 use components of core that's why
// branching here for comments has the least effect on perf.
if (props.comment) {
return '<!--' + encodeEntities(props.comment || '') + '-->';
}

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

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

it('should ignore children with comment prop', () => {
expect(
render(
<Fragment 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 659b456

Please sign in to comment.