-
Hi I declare Card.svelte
<script lang="ts">
import type { Snippet } from 'svelte';
type Props = {
children?: Snippet;
// Style props
'--mb'?: string; // Margin bottom
'--direction'?: 'row' | 'column'; // Flex direction
};
const { children }: Props = $props();
</script>
<div class="row">
{@render children()}
</div>
<style>
.row {
display: flex;
margin-bottom: var(--mb, 'unset');
flex-direction: var(--direction, row);
}
</style> In parent
Or is there more better ways to do put style from parent? |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 1 reply
-
These kinds of properties are not really properties of the component at all. A workaround would be to perform the same logic yourself, i.e. add a regular property, accept styles there and add the wrapper yourself (unless you already have a suitable element for it). <script lang="ts">
import type { Snippet } from 'svelte';
type Props = {
children?: Snippet;
styles?: {
'--mb'?: string;
'--direction'?: 'row' | 'column';
};
};
const { children, styles }: Props = $props();
const style = $derived(
Object.entries(styles ?? {})
.map(([key, value]) => `${key}: ${value}`)
.join(';')
);
</script>
<div class="row" {style}>
...
</div> <Row styles={{ '--direction': 'column', '--mb': '24px' }}>
<span>A</span>
<span>B</span>
</Row> The syntax is not as nice, but this will now check the types. Alternatively you could flatten this to two regular properties, e.g. <script lang="ts">
import type { Snippet } from 'svelte';
type Props = {
children?: Snippet;
'margin-bottom'?: string;
direction?: 'row' | 'column';
};
const { children, 'margin-bottom': mb, direction }: Props = $props();
</script>
<div
class="row"
style:--mb={mb}
style:--direction={direction}>
...
</div> <Row direction="column" margin-bottom="24px">
<span>A</span>
<span>B</span>
</Row> |
Beta Was this translation helpful? Give feedback.
These kinds of properties are not really properties of the component at all.
Adding them creates a wrapper
div
around the component and sets the style there.A workaround would be to perform the same logic yourself, i.e. add a regular property, accept styles there and add the wrapper yourself (unless you already have a suitable element for it).