WebReflection / hyperHTML

A Fast & Light Virtual DOM Alternative
ISC License
3.06k stars 112 forks source link

Booleans render as strings. In conditional rendering this can be unexpected. #381

Closed bdjnk closed 4 years ago

bdjnk commented 4 years ago

A reasonable pattern in rendering is ${value && 'only render if value'}, but if value is boolean and false this unexpectedly renders "false".

Here is a more detailed test case with a couple functional workaround.

wire()`${true && 'test'}`; // test
wire()`${false && 'test'}`; // false
wire()`${(false || null) && 'test'}` //
wire()`${false ? 'test' : null}` //

For a live example see this codepen.

I believe this is happening in boolean handling in the anyContent function

WebReflection commented 4 years ago

A common pattern is also to render true or false, but even more common is to use ternary:

wire()`${true ? 'test' : ''}`; // test
wire()`${false ? 'test' : ''}`; //

Since documentation explains that null or undefined are handled as empty strings, if you want to use:

wire()`${value && 'test'}`

then pass either null or any truthy as value.

As summary, it's been like this since 2017, and nobody complained so far, so this is a major breaking change that I'm not willing to push unless many others would find current documented behavior not good enough.

bdjnk commented 4 years ago

I don't see where the documentation explains that null or undefined are handled as empty strings.

That false renders as a string, and thus can't be used directly in conditional rendering, is likely to confuse people coming from React, given they officially recommend this pattern.

I understand fixing this would be a breaking change, and others have not yet raised it as a concern, and it has trivial workarounds, and thus you aren't inclined to fix it. Still, documenting the current behavior more explicitly might be worthwhile.

WebReflection commented 4 years ago

You are right, null and undefined are described only for attributes, so I need to update the documentation to describe the null and undefined behavior as hole, and also the fact that every primitive, not just string, would land as text.

Will create a ticket in the right repository, thanks for pointing this out.