Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add support for rendering HTML comments #301

Merged
merged 3 commits into from
Jun 9, 2023
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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