Search code examples
sveltesvelte-3svelte-component

How to override a component's default props and export it as a new component in Svelte


I am working on a component library based on Bootstrap and I am developing a Base component which most Bootstrap's classes are defined as properties. It means that some of the properties are mapped to Bootstrap's CSS classes.

For example the below code:

<Base container="lg" mb="2" p="3">...</Base>

will be rendered to:

<div class="container-lg mb-2 p-3">...</div> `

To develop a Card component, I just need to set a few defaults to Base component properties.

I create a new Card.svelte file and import the Base component (component composition).

Also, I exported all components in index.js:

import Base from './Base.svelte';    
import Card from './Card.svelte';    
import Col from './Col.svelte';    
export { Col, Card, Base }

Here is a simple Repl

Is there anyway to define Card, Col, etc. components without creating an individual file for each? Something like this:

import Base from './Base.svelte';

const Card = // Base({ continer: "lg", mb:"3", p: "3", tag: "div" })
const Col = // Base({ col: "6", tag: "div" })

export { Col, Card, Base }

Solution

  • You can merge in the props using the client-side API, e.g.:

    export function Card({ props, ...rest }) {
        return new Base({
            props: {
                container: "lg",
                mb: "3",
                p: "3",
                tag: "div",
                ...props,
            },
            ...rest
        });
    }
    

    REPL example