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/.
A summary of my solution
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)?