2

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?

user364601
  • 51
  • 5

2 Answers2

1

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}})
joshnuss
  • 1,869
  • 14
  • 11
  • 1
    The problem with this approach is 1) Now it's necessary to maintain two HTMLs (on PHP and on the Svelte components) and 2) when replacing the DOM with Svelte data from forms could be lost of inputs could lose focus. – Pier Mar 27 '21 at 01:59
0

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: [...]
}
Stephane Vanraes
  • 14,343
  • 2
  • 23
  • 41