From 8875ca9ef0225564ab6a3739f75cc775f0c761ae Mon Sep 17 00:00:00 2001 From: Jovi De Croock Date: Thu, 23 May 2024 07:52:57 +0200 Subject: [PATCH 1/2] render empty string for null __html --- .changeset/yellow-ghosts-bow.md | 5 +++++ src/index.js | 2 +- test/render.test.jsx | 10 ++++++++++ 3 files changed, 16 insertions(+), 1 deletion(-) create mode 100644 .changeset/yellow-ghosts-bow.md diff --git a/.changeset/yellow-ghosts-bow.md b/.changeset/yellow-ghosts-bow.md new file mode 100644 index 00000000..58d53b5b --- /dev/null +++ b/.changeset/yellow-ghosts-bow.md @@ -0,0 +1,5 @@ +--- +'preact-render-to-string': patch +--- + +Correctly render `null` as an `__html` value as an empty string diff --git a/src/index.js b/src/index.js index 8c4ea39d..72bca146 100644 --- a/src/index.js +++ b/src/index.js @@ -590,7 +590,7 @@ function _renderToString( break; case 'dangerouslySetInnerHTML': - html = v && v.__html; + html = v && v.__html != null ? v.__html : ''; continue; // serialize object styles to a CSS string diff --git a/test/render.test.jsx b/test/render.test.jsx index 05d317a2..ffa8a0c4 100644 --- a/test/render.test.jsx +++ b/test/render.test.jsx @@ -387,6 +387,16 @@ describe('render', () => { ); }); + it('should accept nullish __html', () => { + const Test = (props) => ( + +
hi
+
+ + ); + expect(render()).to.equal('
hi
'); + }); + it('should apply defaultProps', () => { const Test = (props) =>
; Test.defaultProps = { From b64e462a7ee9cf31e11d082a3b35681769e2483d Mon Sep 17 00:00:00 2001 From: Jovi De Croock Date: Thu, 23 May 2024 07:58:45 +0200 Subject: [PATCH 2/2] also address case of array return --- src/index.js | 10 +++++++--- 1 file changed, 7 insertions(+), 3 deletions(-) diff --git a/src/index.js b/src/index.js index 72bca146..9dec64ab 100644 --- a/src/index.js +++ b/src/index.js @@ -55,7 +55,7 @@ export function renderToString(vnode, context, _rendererState) { parent[CHILDREN] = [vnode]; try { - return _renderToString( + const rendered = _renderToString( vnode, context || EMPTY_OBJ, false, @@ -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.'); @@ -590,7 +595,7 @@ function _renderToString( break; case 'dangerouslySetInnerHTML': - html = v && v.__html != null ? v.__html : ''; + html = v && v.__html; continue; // serialize object styles to a CSS string @@ -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; }