I'm new to svelte and I'm trying to get a sense for best practices. I want to create a dynamic form component I can use throughout an app. Each instance of the form will have the same styling - but each form will be tied to different input values in the store, will have different submit logic, etc.
Here's a simple example (that doesn't work):
App.svelte
<script>
import store from "./store";
import Form from "./Form.svelte";
const { inputValueA, inputValueB } = store;
const handleSubmitA = () => {
alert($inputValueA);
};
const handleSubmitB = () => {
alert($inputValueB);
};
</script>
<div>
<Form
inputValue={$inputValueA}
labelText="form input a"
handleSubmit={handleSubmitA}
/>
<Form
inputValue={$inputValueB}
labelText="form input b"
handleSubmit={handleSubmitB}
/>
</div>
Form.svelte
<script>
export let handleSubmit = () => null;
export let inputValue = "";
export let labelText = "";
</script>
<form>
<label for="input">{labelText}</label>
<input id="input" type="text" value={inputValue} />
<button on:click|preventDefault={handleSubmit}>submit</button>
</form>
This example doesn't work, I don't believe the inputValue prop is bound to the text input correctly. Any folks out there with svelte experience willing to share how you'd approach this?
Here's a sandbox:
https://codesandbox.io/s/svelte-form-component-ujnwki
Let me know what you suggest! Thanks.
Not really sure what is exactly is your question but here is the fix for your example to make it work:
you have to bind the value to your component to be able to change it form the child
bind:inputValue={$inputValueA}
and bind the value to the input itself to make its value reactive
bind:value={inputValue}