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 all commits
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
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