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

fix(core): render empty string for null __html #360

Merged
merged 2 commits into from
May 23, 2024
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/yellow-ghosts-bow.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'preact-render-to-string': patch
---

Correctly render `null` as an `__html` value as an empty string
8 changes: 6 additions & 2 deletions src/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,7 @@ export function renderToString(vnode, context, _rendererState) {
parent[CHILDREN] = [vnode];

try {
return _renderToString(
const rendered = _renderToString(
vnode,
context || EMPTY_OBJ,
false,
Expand All @@ -64,6 +64,11 @@ export function renderToString(vnode, context, _rendererState) {
false,
_rendererState
);

if (Array.isArray(rendered)) {
return rendered.join('');
}
return rendered;
} catch (e) {
if (e.then) {
throw new Error('Use "renderToStringAsync" for suspenseful rendering.');
Expand Down Expand Up @@ -682,7 +687,6 @@ function _renderToString(

if (Array.isArray(html)) return [startTag, ...html, endTag];
else if (typeof html !== 'string') return [startTag, html, endTag];

return startTag + html + endTag;
}

Expand Down
10 changes: 10 additions & 0 deletions test/render.test.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -387,6 +387,16 @@ describe('render', () => {
);
});

it('should accept nullish __html', () => {
const Test = (props) => (
<Fragment>
<div>hi</div>
<div dangerouslySetInnerHTML={{ __html: null }} />
</Fragment>
);
expect(render(<Test />)).to.equal('<div>hi</div><div></div>');
});

it('should apply defaultProps', () => {
const Test = (props) => <div {...props} />;
Test.defaultProps = {
Expand Down