Reputation: 29
I’m new to Svelte and loving it! Making a single-component app with a few pieces of UI & shared state is ridiculously fun & easy (coming in with an intermediate knowledge of HTML, CSS, & JS, and beginner knowledge of React).
Ultimately, however, I am hoping to make more-complex apps that would involve a lot of inputs & state, so obviously, I need to understand how to use state between components.
However, I am slightly confused about the best way to make a custom input component and best use the state elsewhere. Specifically, I’m look to create a custom-styled input type="range"
component and use it in a parent.
In the course of writing this question, I did find an approach that seems to work, but I can’t find something in the docs or in Googling that quite matches this case, so I’m unsure of my solution. Here is what I came up with: https://github.com/arrowtype/svelte-slider/.
I started from the SvelteJS Template (https://github.com/sveltejs/template).
My App.svelte
is like this:
<script>
import SimpleSlider from './SimpleSlider.svelte'
export let sliderValA = 0;
export let sliderValB = 15;
</script>
<main>
<h1>A simple SvelteJS slider component</h1>
<p>Slider A value is {sliderValA}</p>
<SimpleSlider bind:value={sliderValA} min="0" max="10" step="1"/>
<p>Slider B value is {sliderValB}</p>
<SimpleSlider bind:value={sliderValB} min="0" max="30" step="5"/>
<p>A + B is {sliderValA + sliderValB}</p>
</main>
And SimpleSlider.svelte
is like this:
<script>
export let value = 5;
export let min = 0;
export let max = 10;
export let step = 1;
</script>
<div class="slider-container">
<input type="range" bind:value={value} min={min} max={max} step={step}>
<span>{value}</span>
</div>
<style>
.slider-container {
display: flex;
align-items: center;
}
input {
margin:0 0.5em 0 0;
}
</style>
In my testing, this seems to work. But, I found it challenging to get there, and I’m unsure of whether this is the best practice.
Should I be doing anything more, like using the svelte/store
module to handle global state (if not, when might I start to need that)?
Upvotes: 2
Views: 771
Reputation: 8982
Honestly, this looks really good and seems like the way to go for me. Why would you want to use the global store? Using it means having the data everywhere available and saved in your app, which sounds like overkill, when the component is only needed in one little form. Doing it this way is better for small independent components.
There are only little improvements for your SimpleSlider.svelte I can think of:
<script>
export let moreProps = {}
</script>
<div class="slider-container">
<input type="range" bind:value {min} {max} {step} {...moreProps}>
<span>{value}</span>
</div>
This approach takes advantage of sveltes shorthand syntax and reduces your amount of code. moreProps
would be if you decide to pass additional properties like disable
for example:
<SimpleSlider bind:value={sliderValA} min="0" max="10" step="1" moreProps={{disabled:true}}/>
Upvotes: 1