Created
November 8, 2022 22:43
-
-
Save mghdotdev/7dd5c7ffe5c71e21630a719a7de6f2cd to your computer and use it in GitHub Desktop.
Lit + FormProxy
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import {FormProxy} from './form-proxy.js'; | |
class MyComponent extends FormProxy(LitElement) { | |
render () { | |
return html` | |
<form> | |
<input type="text" /> | |
</form> | |
`; | |
} | |
}; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
export const FormProxy = (superClass) => class extends superClass { | |
constructor () { | |
super(); | |
this.outerForm = this.closest('form'); | |
} | |
/** | |
* Get reference to the inner form element | |
*/ | |
get innerForm () { | |
return this.shadowRoot.querySelector('form'); | |
} | |
/** | |
* Create proxy on connected | |
*/ | |
connectedCallback () { | |
super.connectedCallback(); | |
this.outerFormProxy = document.createElement('div'); | |
this.outerFormProxy.hidden = true; | |
this.outerForm.appendChild(this.outerFormProxy); | |
} | |
/** | |
* Delete proxy on disconnected | |
*/ | |
disconnectedCallback () { | |
super.disconnectedCallback(); | |
this.outerFormProxy.remove(); | |
} | |
/** | |
* On 'updated' update the hidden form input | |
*/ | |
updated () { | |
super.updated(); | |
const formData = new FormData(this.innerForm); | |
let output = ''; | |
for (const [key, value] of formData) { | |
output += `<input type="hidden" name="${key}" value="${value}" />`; | |
} | |
this.outerFormProxy.innerHTML = output; | |
} | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment