When developing components with Svelte, there are often situations where you need to pass HTML Element’s class attributes to other components. However, a straightforward approach can lead to issues.
<script>
export let class = "";
// 🚨 Parsing error: 'class' is not allowed as a variable declaration name. eslint
// 🚨 Variable declaration not allowed at this location. ts(1440)
</script>
svelte
The error occurs because class
is a JavaScript declaration command used to create class objects. It’s not meant to be used as a variable! This is similar to why React uses className instead of class.
Using className
as below can lead to inconsistency and mistakes when using components:
<script>
export let className = '';
</script>
<Button className=""></Button>
<!-- I have to use className for my components..? -->
<button class=""></button>
svelte
To solve this, a bit of know-how is needed. Let’s look at two methods.
Method 1: className
In the component, alias className
as class
and export it.
<script>
let className = '';
export { className as class };
</script>
<div {...$$restProps} class={className}>...</div>
svelte
Advantages
- It’s declarative.
- Intuitive and good for reusing variables.
Disadvantages
- The syntax can seem a bit unfamiliar.
- The code is longer.
Not very elegant.
Open Source Examples
Method 2: $$props.class
Svelte’s $$props
is a special variable that contains all properties passed to the component. It can be used to easily handle the class
attribute.
<div {...$$restProps} class={$$props.class}>...</div>
svelte
Advantages
- The code is concise.
Disadvantages
- There are constraints on where
$$restProps
can be used. -
<div class="btn {$$props.class}" {...$$restProps}>...</div> <!-- 🚨 The `class` attribute in `$$restProps` remains, overriding the original content. -->
svelte
Open Source Examples
In Conclusion
As always in coding, there is no single right answer.
You can establish conventions that suit your development environment and team’s preferences. Try out the examples on svelte REPL, and refer to open-source codes to make your decision!