Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

How can i bind class as array? #3328

Closed
ashnamuh opened this issue Aug 2, 2019 · 3 comments
Closed

How can i bind class as array? #3328

ashnamuh opened this issue Aug 2, 2019 · 3 comments

Comments

@ashnamuh
Copy link

ashnamuh commented Aug 2, 2019

I tried

<script>
	const classes = ['a', 'b', 'c']
</script>

<h1 class={classes}>Hello World!</h1>

But result is

<h1 class="a,b,c">Hello World!</h1>

I expect

<h1 class="a b c">Hello World!</h1>

How can i bind multiple classes to a element?

@dcrck
Copy link

dcrck commented Aug 2, 2019

Hi @ashnamuh

In Svelte, you can put any JavaScript code between a pair of brackets. This allows you to achieve the functionality you want as follows:

<script>
	const classes = ['a', 'b', 'c']
</script>
<style>
	.a.b.c {
		color: purple;
	}
</style>
<h1 class={classes.join(' ')}>Hello World!</h1>

Also, for future reference, please post your "How do I do <X> in Svelte?" questions in the Discord chatroom. GitHub is really more for Svelte-specific issues and bugs. Thanks!

@hmaesta
Copy link

hmaesta commented Nov 4, 2021

My code became full of .join(' ') since we started doing some AB tests with color variants – for instance:

<div class={[
      'px-10 py-5',
      $AB.black_friday ? 'bg-black' : 'bg-blue-100'
   ].join(' ')}
>
   <h2 class={[
         'text-2xl lg:text-4xl',
         $AB.black_friday ? 'text-white' : 'text-blue-800'
      ].join(' ')}
   >
         Welcome to my website!
   </h2>
</div>

Using arrays in class attribute is a native feature of Vue, but I understand Svelte approach and know that this won't become a thing.

So I was wondering... Is it possible to create a Vite script (?) to "auto-join" array items in class attribute during compile time? (Any initial directions would be great, I am a CSS guy).

@mdynnl
Copy link

mdynnl commented Nov 4, 2021

You could get on with template strings class="{}" or multiple class: bindings.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

5 participants