svelte: Literally undefined class

There is a very small bug. When there is undefined class value and some styles, the element will get literally undefined class.

<script>
	let className
</script>

<h1 class={ className }>Hello world!</h1>

<style>
	h1 {
		color: red
	}
</style>

will produce

<h1 class="undefined svelte-1wsvnfu">Hello world!</h1>

PS: For my components I like nice way to define combination of external and internal classes, just to use true instead of concatenation:

<button
  class={ $$props.class || '' }
  class:MyButton={ true }
>
Hi
</button>

About this issue

  • Original URL
  • State: closed
  • Created 5 years ago
  • Reactions: 2
  • Comments: 23 (13 by maintainers)

Commits related to this issue

Most upvoted comments

fixed in 3.6.11, thanks!

Similarly, I often mix static and dynamic classes. Ideally, I’d be able to write the following:

<script>
  let dynamicClass = undefined;
</script>

<h1 class={"fixedClass" + dynamicClass}></h1>

With a desired output of:

<h1 class="fixedClass"></h1>

The closest way to achieve a similar result right now is with a bit of extra logic:

<h1 class={"fixedClass" + " " + (dynamicClass || "")}></h1>

That’s unrelated to the bug this issue is about, and is something we don’t want to do. We’re not going to mess with what things like + mean in certain contexts. The general rule is that if an attribute is set to a null or undefined value, it won’t be present in the markup. That the style scoping classes mess with this rule is a bug. That "hello " + undefined in javascript is "hello undefined" is not a bug.

When we’re walking through the AST and want to update a node containing class="{something}" to include the scoping class, I guess we need to do something other than just change it to class="{something} svelte-abc123". Using class="{something == null ? '' : something} svelte-abc123" would probably be the most correct.