I new to Svelte and interesting to conditional styling based on props. I have two Svelte components - Parent and Child, just for understanding.
The parent passes props to child - the pt property which should be the padding-top field of child's css. The Parent code looks like:
<script>
import Child from "./Child.svelte";
</script>
<Child pt="45px" />
The Child component has two styles: padding-top and padding-bottom. Depending on what props are passed, the corresponding fields of styles are created. If no props is passed, then the component will have no styles. In the following example, we passed only the pt props which activates padding-top field:
<script>
export let pb, pt;
let styles = "";
if (pt) styles += "--pt:" + pt;
if (pb) styles += "--pb:" + pb;
</script>
<div class="child" style={styles}>
<h3>Hello</h3>
</div>
<style>
.child {
padding-top: var(--pt);
padding-bottom: var(--pb);
}
</style>
Everything works, but is this the right way? Or is there a more effective implementation of this task? Thanks for attension.