svelteprogressive-enhancementsvelte-componentsvelte-3

Progressive enhancement of a Form with Svelte?


I have php page with a working form element that includes selects, inputs fields an so on..
I want the form to continue working without js, but if js is available I would like to convert the standard inputs into enhanced Svelte components.
How would you approach this?
Eg. How can i pass all the "options" available for a select tag to the svelte component that will replace it?


Solution

  • Wrap your <form> in a <div>. When the JS is loaded, it can look for the wrapper and replace it with a Svelte component.

    import App from './App.svelte'
    
    // get the wrapping <div> element
    const wrapper = document.querySelector('.form-wrapper')
    
    // mount your app into the wrapper div
    new App({target: wrapper})
    

    If you want can pass the list of options thru props, just pull them from the DOM before constructing the component:

    import App from './App.svelte'
    
    const wrapper = document.querySelector('.form-wrapper')
    
    // get <select> element
    const select = wrapper.querySelector('select')
    
    // iterate `<option>` tags and extract `value` and `label`
    const options = [...select.options].map(option => ({value: option.value, label: option.innerText}))
    
    // pass `options` as `props`
    new App({target: wrapper, props: {options}})