Tom Konink
Tom Konink

Reputation: 41

Adding CSS custom properties dynamically to svelte components 3.38.0

Svelte added support for passing CSS custom properties to a component in 3.38.0

Which allows us to pass a css property like shown below.

<Drawer --test1="red">

Technically it makes a div like this around your component code:

<div style="display: contents; --test: red;">

What I would like to do is to pass multiple without having to define them like --test-1="X" --test-2="Z" etc.

I would like to place them in an object:

let test = {
    '--test-1': "X",
    '--test-2': "Z"
};

And let the keys be rendered with there values.

The question is, is there a way to achieve this?

Link to REPL with a way to do this would be great.

Kind regards, Tom

Upvotes: 4

Views: 1522

Answers (1)

Geoff Rich
Geoff Rich

Reputation: 5472

I don't think that is currently possible. It would be useful, so you should open a feature request.

In the meantime, you can solve this yourself with a custom wrapper component. See this REPL (relevant code below).

<!-- App.svelte -->
<script>
    import Example from './Example.svelte'; 
    import CustomPropWrapper from './CustomPropWrapper.svelte';
    
    const customProps = {
        '--first-color': 'red',
        '--second-color': 'green'
    }
</script>

<!-- longhand way -->
<Example --first-color={firstColor} --second-color={secondColor}></Example>

<!-- pass as an object using a wrapper -->
<CustomPropWrapper {customProps}>
    <Example />
</CustomPropWrapper>

<!-- CustomPropWrapper.svelte -->
<script>
    export let customProps = {};
    
    // create an inline style string
    $: style = Object.entries(customProps).reduce((acc, [key, value]) => `${acc}; ${key}: ${value}`, '');
</script>

<div {style}>
    <slot />
</div>

<style>
    div {
        display: contents;
    }
</style>

<!-- Example.svelte -->
<p class="first">
    I'm the first paragraph
</p>
<p class="second">
    I'm the second paragraph
</p>

<style>
    .first {
        color: var(--first-color);
    }
    
    .second {
        color: var(--second-color);
    }
</style>

Upvotes: 1

Related Questions