Progressive enhancement of a Form with Svelte?

1.3k Views Asked by At

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?

2

There are 2 best solutions below

1
joshnuss On BEST ANSWER

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}})
0
Stephane Vanraes On

You would make the options available as you would with any other data you use in your frontend: 1) hardcode it in the javascript files (not very flexible, probably not what you need) 2) do a fetch and get the data through an API from the server 3) add them as a property to the window in the php and use that in your svelte app.

window.something = {
  selectOptions: [...]
}