preact-render-to-string icon indicating copy to clipboard operation
preact-render-to-string copied to clipboard

renderToString with {pretty: true} causes undesirable newlines with text nodes

Open stevenle opened this issue 2 years ago • 1 comments

Issue: When using renderToString(vdom, {}, { pretty: true }), text nodes that normally do not have whitespace between it and its siblings are rendered on a newline, which can create undesirable whitespace issues.

Minimal sample project with the issue: https://stackblitz.com/edit/js-imcswy?file=index.js

Sample code:

/** @jsx h */
import { h } from 'preact';
import renderToString from 'preact-render-to-string';

function Text() {
  return (
    <p>
      Lorem ipsum <a>click me</a>. Dolor sit amet.
    </p>
  );
}

const html = renderToString(<Text />, {}, { pretty: true });
console.log(html);

console.log output:

<p>
	Lorem ipsum 
	<a>click me</a>
	. Dolor sit amet.
</p>

Proposed resolution:

When there is no explicit whitespace between a text node and its sibling, the pretty renderer should keep the output on the same line. For the example above, I'd expect an output of:

<p>
	Lorem ipsum 
	<a>click me</a>. Dolor sit amet.
</p>

preact renderToString pretty issue

stevenle avatar Dec 15 '22 18:12 stevenle

Yeah, same thing happened to me. The browser ended up interpreting some regular text with spaces around it.

brandon-lb avatar Jul 24 '23 23:07 brandon-lb