AndrewSunshiny
AndrewSunshiny

Reputation: 11

Svelte js How to pass styles to child (with passability to override)

In svelte, I want to write components in BEM style, so component was stylized by its own styles and then positioned from parent's styles

The problem: to do this, I need to put the component in a wrapper div and then position that div in parent like this

// App.svelte
<script>
import Component from './Component.svelte'
</script>

<div class="positioned_div">
  <Component />
</div>

What would create unnecessary nesting

Another way is to use selector with :global in <style>, but that in not an option because I want to be able to override child's styles.

Instead, I wish I could just pass a classname to component like in React module

<script>
import Component from './Component.svelte
</script>

<Component class="positioningC" />

<styles>
.positioningClass {/* Some styles */}
</styles>

and child component

<script>
let className
export { className as class }
</script>

<div class={`componentStyle ${className}`}></div>

<style>
.componentStyle {/* some styles */}
</style>

Is there a way to get a hash-classname which Svelte creates from the parent and pass it to the child? Are there some packages for styling that could accomplish the same thing (like styled JSX and etc for React)?

Upvotes: 1

Views: 2197

Answers (2)

AndrewSunshiny
AndrewSunshiny

Reputation: 11

For those who are interested, I found a couple of packages for this specific purpose: @naumstory/svelte-true-css-modules and svelte-preprocess-cssmodules

https://www.npmjs.com/package/@naumstory/svelte-true-css-modules https://www.npmjs.com/package/svelte-preprocess-cssmodules

Upvotes: 0

Don Alfons Nisnoni
Don Alfons Nisnoni

Reputation: 51

You can use $$props to access all properties passed from the parent component. You can use spread operator to merge props from parent.

Child.svelte

<div {...$props}>

</div>

or

<div class="child-class {...$props.class}">

</div>

Upvotes: 2

Related Questions