Syntax Video
Svelte 5 Basics - Complete Svelte 5 Course for Beginners
- 0:00 Course Introduction
- 1:23 About Svelte
- 2:45 Svelte Components
- 6:27 Creating a Svelte Project
- 13:26 Our first Svelte component
- 16:25 Props
- 18:29 VSCode Extensions
- 19:02 TypeScript 101
- 19:44 What the heck are runes?
- 22:46 State in Svelte
- 24:32 Binding Values
- 27:17 Events
- 31:39 Derived State
- 38:07 Template Conditionals and Logic
- 50:13 How CSS Works In Svelte
- 57:02 Snippets aka Inline Components
- 1:02:16 Children Props
- 1:03:57 Inline Snippets
- 1:07:35 Each Loops
- 1:21:31 $effect & lifecycle
- 1:30:07 Debugging With Inspect
- 1:32:46 Animations
- 1:37:22 Complex State
- 1:42:22 State with Classes
- 1:45:30 What We Didnāt Cover
Course Introduction
hey what's up this is Scott from syntax and in this course I'm going to take you through the basics of spelt 5 that's right the perfect person for this course is somebody who has a bit of JavaScript experience you've got node installed you know how to use npm but maybe you haven't ever seen felt 5 you just heard about it today or maybe you're a react user and wanting to see what the hype is about now we're going to take you through the basics this is certainly not an intermediate or an advanced course we're going to show you the syntax we're going to build an easy little app but the most important thing is we're going to take it step by step we're going to explain deep what's going on so that way you have all of the tools that you need to really like Foster your creativity so that way when you start to work on your own applications you at least know where to look to find techniques and we're going to be talking about all kinds of things from the new state runes effects components even the basics of how you create a spelt component we're going to be talking about Snippets we're going to
be talking about even animations that are built into spelt so if you would like to learn spelt 5 this course is broken up into chapters if you want to see something specifically you can use that chapter specifically to learn that little bit the code is all available on GitHub and as always nothing hidden behind a pay wall here at syntax so follow along as we dive into spelt 5 it is my favorite framework to work in okay so before we get into any code here or start working on our app I wanted to spend some time really talking about what makes spelt and spelt 5 in particular interesting if you are already a spelt user you can pretty much skip ahead until we're writing code here because you probably know these things or maybe you just want some more information here the big reason why spelt is interesting specifically is because it's a compiled language when you write spelt templates even though it really feels like you're writing HTML
About Svelte
you're having this HTML in simplified JavaScript being able to be compiled into JavaScript HTML and CSS in a way that makes it so we're not having to ship as much Library code as you typically would now all of the examples in this course can be done by heading to spelt dodev and clicking on reppel and then working in the code directly there since I'm recording this before spelt 5 has been officially released I'll be using the preview version which looks a little bit something like this now I will recommend that you run the commands and do all these things locally instead of using the repple but sometimes it's nice to just get up and running and have some code in front of you working and I totally get that so if you want to use the repple there's nothing going to stop you from being able to do that in this course now before we actually write some code let's take a look about what makes felt interesting like I mentioned because it's compiled we can have things like this this is a non-standard template tag this is not JavaScript this
Svelte Components
is not HTML this signifies a template tag inside inside of spelt and what happens is is that this becomes a compiled reactive variable when this variable changes specifically the variable will update in the HTML now this differs from something like a react based framework where in a virtual Dom react based framework those types of things you have a function and your component is a function and that function will rerun every single time something has changed whether that's a prop or whatever that function is going to rerun with spelt we're tracking values not components so if a prop changes that value of that prop and anything that relies on that prop changes but the stuff inside of this is not rerun so you don't have to worry about how many times your component is rendering because components aren't
rendering here it's values so that's a bit of a mindset shift if you're coming from other Frameworks and if you're not coming from other Frameworks just know that we have variables that are defined with State and when you define a variable with State and that variable is updated it is then updated everywhere it is being used now we mentioned that this is compiled and because of that it means that whenever we compile a spelt file it outputs to actual JavaScript that you can read now you will see that there is some things like where you're importing this dollar sign from spelt internal client now unlike something like rea you're actually getting real readable JavaScript that does much less at the library level and much more after being compiled and if you are go into the reppel you can actually see what this looks like when it's compiled to the server versus the client if the CSS has been injected or external whether or not we're in Dev mode you can see that Dev
mode just looks a little bit differently here and what's also cool about spelt is that we can write our CSS HTML javascrip script in the same file so we can do something like style button background red and the background obviously turns red because we've written the style directly in our template but in addition to that the CSS output has a scoped class on it we're going to dive into this so much more once we start talking about CSS in general and the general strategy about working in CSS but you can see that we get a distinct Java JavaScript and CSS output as well as this a which is an abstract syntax tree uh this is what these spelt files are outputting so it's a really interesting language overall and what it allows for is exceedingly simple component syntax meaning that everything inside of spelt is often
times much less code than other Frameworks because they can tuck a lot of that complexity under the rug of the compiler it also means that we end up having smaller component files less framework code that we're importing and just generally a nicer more similar to HTML feel for everything I like to describe spelt as being HTML with kind of JavaScript sprinkled in rather than JavaScript with HTML crammed into it right that's just how I think about it so let's go ahead and let's get started by creating our project Now to create a spelt project you use the utility npx this tutorial course assumes that you have node and therefore npm installed and it needs to be a version that's new enough that has npx which is honestly most of them at these days and what version of node I'm using is 20.6 that's a bit newer of a version you don't need that newer of a version I'm sure 18
Creating a Svelte Project
would suffice just fine but this is what I'm using if you want to follow along exactly now to install spelt we do npx SV create and this is going to create a new spelt kit based site now spelt kit is the app framework for spelt you don't need spelt kit to write spelt sites but it's often the easiest way to get up and running especially if you're building a website and it's a great framework overall so we're going to be using it that said we won't be doing many spelt kit specific things in this course other than just using the general structure of a spel kit app so npx SV create you can see it's going to say hey it's going to first install SV now the version may be different considering I know they're actively working on this before release we'll just say why and if these screens are a little bit different for you I'm sure there's a chance they are but for the most part it should be the same so it's going to first ask you
where you would like this project to be created if you don't have anything here it's going to create this project in the folder that you are in right now since I'm in my root tutorial folder that would be a bad idea so I'm going to create a new folder which is just going to be spelt 5 course whatever you would like to name this you can name this that that's going to create a new folder and install your app inside of that folder now the options are spel kit demo library or minimal we're going to do minimal hit enter just because we want as little code as possible we're focusing on spelt here now you can use any of these op options for type checking I tend to go with just the typescript syntax cuz that's what I'm used to it is what we will be using in this course but I won't be focusing too hard on typescript topics here it's just a nice way to be you can also use JS doc style comments and for what we would like to
add to our project you'll see kind of some interesting options here from drizzle to Tailwind playright vest now last time I ran this utility it it had them broken up into different categories so I do want to stress that this may look different by the time you get to this and because of that and because we're keeping it simple in this course I do just want to add prettier and eslint these two will at least give us the formatting that we need and want while we're working in a new code base right we can tell if something's going wrong well we're not going to be writing tests or doing anything with Tailwind or databases or anything like that so just hit enter now it's installing everything and we should be getting up and running in just a
second okay there we go let's change directories inside of our spelt 5 course Let's do an install if you're using npm you can do npm install you can also use pnpm or yarn or any of these things bun if you know what those stuff is but for the most part I think most people are familiar with npm so we'll stick with that okay so npm installed and I believe it actually probably installed our dependencies anyways for us yeah installed the dependencies already but hey you know what I kind of always love running npm install anyways regardless just in case now what we want to do next as it says is npm run Dev now it gives you this option to hyphen hyphen open and we can go ahead and do that too just so that way it runs inside of the browser window that we had last had open and that I don't have to copy and paste
um a URL here for us so we're going to do npm runev and this site is vit based so it is using vit as a backend build tool and everything like that and this is great this is what we get when we have our spel kit site uh we're also getting out of the box serers side rendering meaning that our content even though it's being written and spelt in JavaScript is actually available in the Dom right away now you can turn this off and go all client side render you can go pre-rendering you can do static sites you can even do a combination of the two if you are uh having your sites based on routes again these are all spel kit specific topics that we won't be covering too much here now I'm going to first and foremost after we have this up and running I'm going to open this up in VSS code you can drag the file into vs code you can use code forward slash to open it if you have the command line utility installed and I'm going to do
that here we are okay so I'm going to make my code nice and big for you because I think it's important to be able to see the code inside of these videos and what we will also do is Bop this open over here and maybe even close this make this a little bit more and this one a little bit more there we go okay so check this out this is a spel kit on I'm going to close the welcome screen my theme that I'm using Color theme is syntax FM so if you're a fan of syntax we do have a syntax theme for vs code and that's what I'm going to be using so first and foremost we have our spel kit 5 site it actually works inside of the SRC folders all of our files this is pretty much everything we need to worry about right now and for the most part we're going to head into routes now routes where we have plus page. speld is going to be our page right here and in fact welcome to
spelt 5 save this you can see it updates right we're clearly in the right file now again we're not going to be focusing too hard on spel kit specific things so if you want to learn more about this page file in the routes folder and the lib folder and stuff we have content on this channel as well as the official documentation is a great point to do that and I think it might be a good opportunity to do a new spel kit to tutorial Course once uh the next one is released or spelt 5 we'll also be covering a lot of transferring spelt 4 sites to spelt 5 on this because the syntax. FM site is built in spel kit and you should get a nice dose of spelt and spel kit there okay cool really cool cool stuff awesome stuff this is our introduction here let's go ahead and write our first bit of spelt code right so this is just a page file and in typical spelt files you end up having a script now the script is where you do
Our first Svelte component
your Imports it's where you do your JavaScript it's where you set up your state it's all of that stuff but what we want to do in this first section is create our own spelt file and we want to use it as a component so I'm going to do that I'm going to actually do it in the exact same folder inside of the routes folder and this will just be header.
spelt right most sites need a header right and can hit enter again we're going to want to have a script here now the only difference between this script and the last one is I'm going to do Lang equals Ts that gives us typescript support if you do want that if you don't just omit this Lang TS and we're going to say H1 hello from header okay this is our component and instead of our page dosf what we'll want to do is import this header file and then use it as a component so if we import header from slhe header. spelt notice that you do need the doel extension here this is going to allow us to utilize this like a component just like an element now if you're familiar with react or view or any of these other Frameworks this kind of uh importing a component and using it
should be extremely common place for you right nothing that you haven't seen before the only differen is is that we're importing a DOT spelt instead of a jsx TSX JS file whatever right and it works nicely because it's pretty explicit that it's a spelt file and the convention is to do an uppercase like this like this so you don't have to do it that way but that is the convention cool so you can see here our HTML is updated hello from header exists and all we're doing is importing this component and using it like this now something that differs from other Frameworks to spelt is that often times in spelt each component is a single file I know in react land sometimes people like to have multiple components in a file or subcomponents or things like that there are techniques that you can do with spelt like that using something called Snippets which is a new feature in spelt 5 but for the most part you are using what's called a single file component and anything that you write inside of
this component ends up being scoped to that component and that component specifically that includes CSS as we mentioned right so here we are and again I'm going to add a style tag in here because in spelt land this is the typical anatomy of a spelt file right we have a script tag up top you have your HTML here and you have your CSS feels very HTML right and because everything except for maybe how the reactivity stuff works since felt or the template tags does feel very HTML forward so let's talk about something called props now props exist in most Frameworks these days and a prop is essentially when you pass a variable from somewhere into a component and typically that is done with the prop is equal to prop value format like this I'm getting some red squigglies because this
Props
prop does not exist right but this is the typical way you do that and then inside of your header you would have access to the variable there meaning that you can pass one thing down from one to another that's like a very common way to pass information from component to component so here's how we create props inside of spelt the first thing I'm going to do is I'm going to create a prop inside of the header component and to do that you say let and then you have curly brackets because this is going to be destructuring is equal to dollar sign props like this this means whatever variable we create here will be a ailable to have information passed into it so if we want to say name that means that in our page doel we can say name is equal to something like Scott okay so this allows us to pass the value a string of Scott
into header and in our side of our header we should now have access to that and we can replace the words from header with our template tag of name and our output now says hello Scott notice how we do so within curly brackets in spelt anything inside of curly brackets can be a variable it's a JavaScript expression right very similarly to how you use this in jsx and react land this is a JavaScript expression meaning you could do something like name is equal to Tim and it's going to be false right name is equal to Scott and it's equal to true so this can be a JavaScript expression any way you have it now might be wondering about syntax highlighting and stuff like that if you type in spelt for vs code extensions the one you want is spelt language for or spelt 4 vs code do not install spelt intellisense it pops it's it's deprecated it pops open a bunch of
VSCode Extensions
Windows when it shouldn't and spelt extensions for spelt also contains this spelt intellisense the only one you need is this official check marks felt for vs code okay that's what I'll be using here okay back to the program okay so we now have name coming in from props now typescript folks out there might want to know how we give name a type cuz right now it's type of unknown again we're not going to focus too hard on typescript stuff but I will call out when we need it to do that in typescript you just do a colon and then you have access to your types like this and so now name is the type of string and we know it's a type of string so when you define types inside of spelt you're often doing so in the pretty standard way that you define types for a variable okay I will be leaving the typescript code in here uh if you find it obnoxious feel free to not use it but I do like the assurance that it gives me that I'm writing the code correctly now you may have wondered
TypeScript 101
What the heck are runes?
about this little weird dollar sign props syntax the dollar sign inside of spelt 5 is something brand new and it's called runes in the past you exported a prop and it was always kind of confusing to people inside of SP they really leaned hard into the dollar sign and then what you're using and then a function so dollar sign props to create a prop dollar sign state to create a state uh there's derived there's effect there's a whole bunch of things and we're going to be talking about all of those throughout this course we'll be talking exactly what they do and this course again is going to be really getting into the basics of spel here we're not going to be going super Advanced use cases but I do think it's important to notice that whenever you see this dollar sign props you're seeing that this is like this is a spelt language feature declares a prop that the component accepts right so again they're called runes you'll see that in the documentation a rune again is just kind of like a symbol and in this case it's the dollar sign symbol letting you
know that there's something important going on here okay sick that's all great uh we have now our first spelt component which is header dos felt we have our page now before we get into State let's go ahead and head to our page dosf felt and I want to show you something else we can do with props here now just like we can do anything inside of spelt scripts that it's JavaScript we can create a variable something like let name is equal to Scott like so and then you can use that name value inside of your JavaScript Expressions inside of your template tags and in other JavaScript Frameworks the way you do that is like this however the coolest thing about spelt and not the coolest thing but everything's the coolest thing about spelt one of the cool things about spelt is that this actually works how you might expect it to other Frameworks where if you and I'll save this if you do it like this that's the equivalent of saying name is equal to name other Frameworks might take this to be a
Boolean value for some reason that never makes any sense to me so if we want to pass the same uh value name into the same prop name like we have name here we're passing name into name this is the syntax for it it's so concise and lovely and I feel like everybody should adopt this I don't know why they haven't by now and likewise we can come in here and you can see that this still doesn't change everything is working as expected now to reiterate too even that these are just JavaScript Expressions let's even do some real JavaScript here like if we wanted to uh replace the t's in my name with uppercase T's or maybe even replace them with uh X's or something right we could do name. replace and and we could replace t with X like this and obviously if we wanted to replace all of them You' replace all and you can see this is powerful because we can write some JavaScript Expressions directly inside
of this template right that's pretty neat okay now let's get into the part where we're talking about State now state is fascinating inside of spelt because in the past State used to be declared as well it was a value right and in this case if we were to find name like this name would be a state value and it' be reactive you would to change name that would change reactively but in Sp five they did away with that and now we're using something called state which is another Rune so if we wanted to try this again like let name is equal to Scott we could say let name is equal to dollar sign State and the default value of our state comes inside of here and is just Scott like this okay so let name is equal to State Scott now people who are familiar with spelt 4 might see this as a downgrade but one of the things that was hard with spelt 4 was that it was often ambiguous which variables were
State in Svelte
changing and which ones weren't how they were changing what they needed to do and it often sometimes led to either confusing or non-performing code so with spelt 5 we now have dollar sign State and we can set a default value like this now let's get some fun stuff going on inside of here and show you how we can make this extremely easily reactive we can say input so it's just a straight up text input and I'm sorry I'm not going to do a whole lot of fullon HTML accessibility stuff in this we're not building a label I'm I'm focusing really hard on spelt 5 specific features and spelt specific features so all of your accessibility uh needs and everything HTML best practices should still apply right so the type is of text the input type of text and we're going to use this nice little directive on an HTML element called bind and if we bind the value of name and what this means is
Binding Values
that every single time we update a value of this input the name value will update and this therefore will pass into the header and the header will update so by using bind value we are binding whatever the value is of this input to this variable you can see it even starts off by default as Scott so uh we can say Wes and notice how this updates immediately right we didn't have to do an unchanged function to update the state or anything like this it's a nice and simple bind it works super well and this is one of the nicest features of spelt overall is that we can bind variables you can also bind other things right you can even bind a variable to an HTML element so that way you get access to the element itself as a variable that's pretty cool um there's even there's a lot more there but bind value is the way you most commonly use this so here we go but again because we have a JavaScript Expressions inside of
here anytime we type a lower key T what do we get we get an X in the second one so again if we start typing Scott so you can see how that reactive JavaScript expression is super nice right so input type text bind value name that's State variable okay let's dive into some more state things like for instance let's say we wanted to have a status so we can say let status you can often think about these as like whether or not something is open or closed right you could say date and this could be open and for typescript folks we Define the type again by just typing the variable itself so we could say this will either be open or it will be closed okay and we're getting red squigglies because I don't have a l equals TS here there we go now one thing you'll notice though that name will have a type because it is
inferred from this where this would have been inferred as a string unless you you know told it what it was this is pretty much standard inside of typescript overall so we have our status now and let's say we wanted to have our status displayed we could just have let's have even like a paragraph tag here that's says the store is now status okay the store is now open let's make a button here to change that we can have a button which will be toggle status now with something like this we can start to use events now in spelt past you would do this with onclick like so right you use the on directive onclick and in react jsx land you for some reason do onclick like camel case like a JavaScript style but we're working with HTML here folks so we get to do onclick like this onclick
Events
could be then referencing a function that we haven't created yet Perhaps it's named toggle so we could say function toggle and this is just a function like this and here we can update our state by saying status is equal to and then we can do just a turn error operation here so we can say status is equal to if status is equal to open then make it closed otherwise have it open right so that way if status is closed it becomes open or status is open it becomes closed now you'll notice a difference between other JavaScript Frameworks in spelt in that with spelt you actually update the the variable itself you mutate the variable and that actually is what triggers the reactivity there is no dot set state which means that these things when you
declare them like State like this they largely function and there's caveats here but they largely function just like straight up variables right and this is really nice because now we don't have to have this whole destructuring of a set State and a state itself we don't have to have a a state creation that way we just end up having a variable that you can have reactively so if we want to try this now this should work if we toggle our status open closed the store is now open or closed really nice and this works super duper well it's pretty easy to read right we just have our simple toggle function again we're just updating a variable and that variable is reactive because it's a state now let's go ahead and show you another cool trick because normally this is how you do it right you have a function it's named toggle that function just you know it describes what it does but sometimes you're in a component that is so specialized and it has one onclick function right like the only point of
this component is that it runs an unclick or even just that there's only one event and in that case let me comment this out and you can actually name this function onclick and just like what we did with props before we can name this onclick and you will see that you can just do it as brackets onclick that's a nice ni little shorthand I end up using this all the time specifically because heck a lot of these single use comp you know you build a component it's so scope to what it does and it has one button it makes sense to have the onclick be named this oh hey you click the button it's what it does right now in addition to that if you wanted to get in line with it I know this is a common technique in react land you can do that as well where you say onclick and again we have access to JavaScript Expressions inside of a bracket so we could say onclick and now I'm running a function and that function could in fact be this variable setting code right
here okay so this right here is the inline version of something like this and you could see it will still work here this is the one being utilized and the other one will still work as well so you have a lot of different strategies here that you can do for these types of things but as you can see onclick will work just like this onclick will work just like this and we can do all sorts of stuff if you're the type of person who likes to throw all your code in the template right this is typically how you'll see it being done I know that's fairly common in other Frameworks if you're the type of person who likes to keep it all separated this is how it works right here and if you're the type of person who likes to be very explicit with what it does you can name it what it does and pass that in cool so this is State inside of spelt now there's a lot more here because we have things like derived state we have Frozen State we have these kinds of things we're going to be talking quite a bit more about
that and that's what we're going to be talking about next so this is a state it's pretty amazing right it functions very nice and easy let's actually talk about state in a different way because you can actually get into some more interesting scenarios with different ruins with State and I mentioned that we're not going to be getting too much into the Super Advanced use cases in spelt but this is a fairly common one okay and this would be like let's say you have a value and a value that depends on another value and that's reactive the the best example I can come up with is you have a shopping cart right the shopping cart has numerous items that have a price and in the very most barebone simple example that might just be an array of of prices right and then you have your total that total would always be calculated by adding up the same prices if you add something to that array you change something in that array you want that total to always stay
Derived State
in sync so this is a derived variable as in it derives its value from another state so a cool example of this might be let full name is equal to and then we can say dollar sign because again this is a rune this is something special derived and what we could take access in here is say name plus a space Let's do an empty space and then plus uh oh not not a we'll do this tulinsky as a string you can do whatever your last name is and now we can use the full name down here and we can pass that full name or we can just put it into we're we're just dumping this into HTML right now we can just put it in H2 and this H2 you can see now says Scott tulinsky now what's great about this is that anytime the name changes then full name
will change as well so if I wanted to say Courtney tulinsky you can see that hello Courtney the X obviously is there from the T but she also gets Courtney tulinsky here and this is all derived from this value you could obviously do it where the full name is hard encoded into a template string in here but this is a kind of trit example for how you might use this like I mentioned you could you could actually even run a function inside of a derived bu and have that add up the totals of something you could have a value that is always going to be staying in sync and you want it to be possibly reused elsewhere uh throughout your code and so it's not just being used once in the template or anything like that you'll end up finding yourself using derived values any time you have a state value that depends on the value of another state now that we've dove into some deep deeper topics on state I'm going to dive into one deeper topic inside of props because we
talked about props looking like this now granted this is the types script version without this it would look you know just like an object definition you might be wondering how do we do optional props inside of SP because right now name is a required prop and you can tell by the type signature that it needs to have a value right not only that we're actually using it this method depends that it exists so name needs to be there and typescript will yell at us if we remove name from header right there we go and it'll say uh name is missing in type okay what about optional props props that you might not have well those types of props can be done using something like this so if we Define another prop name we can just have this be a fake name so so here we have fake name and we can give this a we can say this is a string and you can use the typescript syntax of having a question mark in here now we aren't
using fake name here but let's come to our page and you'll see that typescript now knows that fake name is optional granted we can pass fake name in here and it will know that it's optional right however how do you do this with typescript or without typescript I should say without typescript you could give this a default value and you could say the default value is something like null obviously you'd have to update the type to say that it could be string or null but then what what you have here if you don't have typescript you're not using that you have something that has a default value and if you then pass another actual value into it it will then show up so again let's drop this in here we could say fake name just down here you'll notice that nothing is broken right here if we come into our page header is not complaining that fake name doesn't exist but if we do add a fake name is equal to
Wes then it will be output okay so you can have a default value set for this if you set it to be null it's like a totally optional prop and then you can do your control flow to check to see if if fake name exists or not and then display it or you can even have a default value in here like Wes and we can remove this null this still says the prop is optional so we need that it could be undefined and if we head back to our page you could remove fake name from from here and it will always display as Wes so a lot of this stuff does feel like it is very just JavaScript stuff right if this is how you define a default value in a function or anytime inside of JavaScript and it works the same way inside of here just likewise when you define types it's the same as defining types in JavaScript people often describe spelt as being magical and the Only Magical things inside of spelt are just these kind of things like this where we have props or this template syntax but for the the
most part the way it works is real JavaScript real HTML and it's combined in a way that just feels really great Okay cool so the next topic we're going to be getting into is logic then we're going to be getting into something called Snippets then life cycle methods and then we're going to dive into things like animations and all sorts of cool stuff because spelt 5 has a lot you can do out of the box we're going to be focusing largely on stuff that you might need in most applications but largely getting up and running in spel 5 so if you need to take a break now is a good time to do that however let's get into it where we start talking about using logic inside of your templates okay let's keep this going and we're going to dive into template logic here because we have done a little bit with these template tags we've shown you how you can use JavaScript Expressions but unlike react and other Frameworks spelt has the ability to use real template tags for things like if statements and Loops which means we don't have to do
Template Conditionals and Logic
any of the weird double Amper sand tricks or turn areas where you shouldn't have to or even a map for a loop because you needed an array for some reason right you don't care about those little details with spelt what you care about is the way that the template reads and the template reads using template tags such as uh pound if or pound each those types of things and there's a handful of these template tags that well will make your code do the types of things you need it to do okay so let's actually head to our page.
spelt once again and you'll remember that the way we had this working was we had a name a status a full name I'm going to start getting rid of some of this stuff in favor of some new state New State in which we're going to be using to build an actual pseudo app here right nothing crazy so let's go ahead and just get rid of this stuff and likewise I'm going to get rid of all this stuff as well we'll just clear this out right get a nice little if if you want to make sure that you have this code for later obviously duplicate this file or make a new file or something but I want to keep moving here and we're going to be using a lot of the techniques we showed before anyways so let's go ahead and what we're going to create first is a formore state now actually let me do this in camel case I prefer snake case that's a me thing so I'm not going to force that on you here in this course so I'm going to do everything in camel case like uh most JavaScript folks do so form
state is going to look like this where we have a state and inside of our state we're going to have an object where that name is going to be an empty string first and foremost and then we're going to have another property which is birthday which is also going to be an empty string okay so this is just the general form State now another thing we can add in here is a step which Step we're on in the form because this will be a multi-step form so we can just just call this step like this and the initial value can be zero and lastly we can have another property which is error you know potentially if there is an error in this form this is the entire state for this form now if you were doing this as a serious project you might have like a Fields sub object here but I'm going to keep it fairly simple that way we don't have to get too deep here okay so this is our form State and this is what we're going to be using for most things now I
want to First and foremost say uh we're going to have a main tag here and inside of our main tag we're going to say what step we're at so step is equal to and inside of this template tag we're going to say form state. step okay we can save this you can see now says Step Zero I'll even bump up the size here okay nothing crazy there so let's go ahead and talk about how we can do this with first if statements and then eventually we're going to get into things like Loops right using each which aren't really that crazy but I think it's good to take a step-by-step approach so if we want to do an if statement it's as simple as saying pound if and then the conditional statement that you need to have so if we want to say form state.
step is equal to zero so if the form state. step is equal to zero and then we can finish this off with a for slash if right this is a basic if statement inside of spelt nothing wild here inside of this very first form step we're going to have a div inside of that a label and the label is going to be for name it's going to say your name and we're going to have an input here the input type is going to be of text it's going to have an ID of name and the value is just like we did before it's going to bind the value we're going to bind the value and this time you'll notice that we can actually bind the value of a nested property inside of an object so in this case it's form state.
name okay so this actually works anytime you want to do this in fact this is one of the reasons why people like spelt form and uh variable binding so much right you could have a deeply nested object that represents the total shape of your form and have all the values bind and then you don't have to have all these individual update functions for your fields and you can still have what would be considered a controlled form because you then have access to these form values throughout your code and you can do things like if statements on them so let's go ahead and now have a button in here and this button is simply going to just say next okay and we're going to have an onclick event here and this is going to say onclick is equal to and then we can have an inline function for now just cuz we want to see this in action we're going to say if form state. name is not equal to an empty
string then what we can do is we can in increment our form step form state. step plus equals 1 now a lot of people don't like the plus equals thing so you could always do form state. step plus one here if that works just fine as well but where you're going to see here is that because the if statement is checking to make sure that that form State step is equal to zero if I first try to click this you'll see nothing happens and then if I enter my name I can click next and it disappears entirely and step increases by one now this doesn't persist or anything so if I refresh the page we're back to normal now another thing you could do in this if statement here is just add an else and if the form state name is empty you can add to your form state.
[Music] error form your name is empty please write your name okay great great little error message right here right wow okay super cool and we should also add a format. error to clear this out in case we have a non- errored form state okay nice and easy let's actually add that error into our form as well and I'm just going to throw it right up here at the top we're not building anything beautiful here and before I type this I think this might be a good opportunity for you to just try to get this working now granted this should not be a hard lift but if you're new to spelt you want to make sure that you get it right try to code this with maybe even not looking at this code below and and just do your best to write an if statement otherwise what we do is we just do pound if and then we were to say form State
DOT error so if the form error exists and then we can finish off this if block here if the form error exists as a well a nonn value or empty string falsy value right if and then what we'll want to do is display a paragraph with a class of error and just output the form state.
error itself okay nice and easy so this way now if we click next you can see it comes up with an error here now it's shoving the UI down this isn't a type of UI I would typically build if I'm building a fancy form but of course we're not doing that here next thing I want to do is add on to our if statement here for our form step now this code is going to be kind of wet for now we're going to make it drier later on but I don't want to spend too much time on those details while we're just learning these template tags and so likewise if you have an if you can also have a colon else okay and an else block functions the exact same that you might expect an else to function in JavaScript in addition to that you can also do an else if and then if form state. step is equal to one right now we're just kind of hand coding each form step individually
then you're going to want to show what we have next and likewise what I want to do is just copy this whole first one here because we're going to utilize quite a bit of this for now until we make this drier and we're going to change the only thing we're really going to change here is the uh we'll say that the label for is bday the ID is bday your birth day and the type is no longer going to be text but it's going to be a type of date okay and we can keep this bind value but we're going to change it to birthday okay nice and easy and likewise if we come down here we can say form state.
birthday if it's an empty string or if it's not an empty string increment and then reset the error if it is your birthday is empty please write your birthday wow these error messages fantastic right okay so again let's click this you can see we get an error okay let me actually write my name Scott next all right now step one uh your birthday and then we have this form we can click next and now we're at step two now one thing you may be noticing while we're doing this is that we have a zero based indexing here so the whole step one two three thing um there's there's a kind of uh multiple ways you could solve this you could just start this with step one you could show this as plus one and you can adjust these numbers when we start getting into doing this as a loop though we are going to have index based zero which is why I'm keeping this as zero for now and we're just going to add a plus one here to the form state. step just for the display okay so just by
doing this simple expression here that just fixes the display of it because again we're going to eventually take this into a loop and I want to keep that zerob based indexing at least for now okay super cool and we should have this all working now obviously if you're the type of person who writes a lot of code framework or otherwise you're going to see so many places we could stop repeating ourselves simply just checking the field to see if it's empty and then either incrementing setting the error or just changing a simple uh string here this obviously could be all refactored into a single function uh but that's not super important right now what's important is that we have learned that you can do a pound if and a pound else if and a pound else and then you always need to finish it off with with a forward slash if this is just like a closing of an HTML tag and this is very typical you'll see this forward slash anytime you need to close a block of a spelt tag whether that's a loop or an if
statement or anything there's even uh a promise one where you can do await right pretty neat so this is a great introduction to template tags and uh conditional logic within your spelt templates I love this about spelt because it's so readable right we're not having Amper Sands all over the place and just kind of ambiguous things we're seeing straight up if form state is equal to zero if form State exist the type of things that you typically write and this is one of the reasons I like spelt so much now before we get into the next template tag we're going to cover which is looping with each I want to talk about CSS now CSS in spelt is also pretty amazing believe it or not I think most things in spelt are amazing but if we want to have CSS you can have a style tag directly in your single file component and we can Target this with a simple class here error is going to get a color of red okay we can click here you can see that that is now the color of red but what I want to stress about CSS inside of spelt is that it is
How CSS Works In Svelte
tightly scoped to the component itself and any CSS classes that are defined in children components or parent components of error will not get this color of red because anytime we write CSS in a spelt component it is only affecting what is in the component itself and now this could work for any selector let's say we have a div you could just have a background of blue right and this is going to have any div and give it a background of blue this is a paragraph This is a paragraph right so this is the background of blue any div within this component is going to have a background of blue but let's go ahead and really quickly add back in our header component here and I'm going to quickly set the name is equal to form state. name okay and we'll go ahead and modify this header real quick we can get rid of the hello part we can get rid of the replace
all and even the fake name stuff let's get rid of all this okay we can simply just have a div and inside of that div is going to be an H1 and inside of this H1 we're going to say pound if name if we can have an H1 name form okay so if I type my name it's going to have names form so I can say Scott and this is now Scott's form but again this is inside of a div and this is inside of a div but because the style is scoped to that component this div right here does not get any of the CSS this is a feature that could be considered frustrating to newer Dev developers of spelt but season CSS practitioners will find this to be incredible because we have the now the total freedom to write Global CSS for
when we want Global properties but we also have tightly scoped CSS meaning that if you end up having a component that is this simple we don't have to worry about naming classes a common thing that you might do in other Frameworks is this is the header so you give this a class of header and then you come to your CSS and you do header right now we have the same name three times in the file the class the class even though that class is not leaking out or maybe it is maybe you're even using a component to encapsulate that like styled components so in this case you could even just say div is a background of red um you have to have a semic clone there and you can see it it just gets it and that won't leak out of this component meaning that if you have very simple component trees then your CSS uh selectors can be simple as well this works by actually adding special classes to each div you can see this or each item anytime we give a selector to
something it gets this scoped class and that CSS is added as actual CSS with that scoped class this all happens behind the scenes in a super automatic it's one of my favorite features of spelt just like so many others but it it's really really great for productivity when you're writing CSS now addition I mentioned that these Styles don't leak if we get rid of this red one you can see obviously this doesn't turn blue based on what we just talked about but what if what if and I don't recommend this because I recommend putting these Styles in a global stylesheet but there are certainly scenarios where maybe you have some code that's being generated um and that code is some child and there's some classes in here and you might want to uh give this a class and it's just not being scoped correctly well you can actually add Global CSS into your stylesheets with the this colon Global function selector function here just like this and now if I type in
my name here you can see that the blue now leaks out because I've said that hey this div is global now who knows if this will ever change based on the scope property coming to CSS I'd have to imagine it just changes how it happens behind the scenes but again this is how you do it if you want to have Global CSS you do it just like this all right let's get rid of this entirely here and let's go back to the way our form looks and I do want to modify this header bit and also what I want to do I want to move the error message first thing of s I'm going to move the error message below the form I'm tired of things uh pushing other elements around because I think that's bad ux and even though we're not focusing on good ux here I it just bugs me right okay so the form error is now below the form doesn't push anything out of the way but if we start typing it's going to push the form down so let's head to our header and let's change this if statement because so far
we've only shown if statements inside of wrapping around elements now you could put this if statement directly inside of here right so you could do um inside of the H1 you could have the if name like this right and let's get rid of this there's nothing stopping you from doing this now you may notice that this could probably be written as a single inline one and typically that's how I would approach this as well and if we're being honest here I would do this in a Turner so that way I could say um if the name exists then show the name otherwise just show um a string that says user okay let's refresh this user's form Scott now it doesn't bump anything down now it all just works right all right we're building ourselves a nice little form here we have if statements going we've learned quite a bit about how CSS Works inside of spelt and we're ready to
start getting into looping before we get into life cycle things like side effects uh on mounts and those types of things because I know that if most people were to look at this you'd say ah if form step is equal to zero this is not sustainable if we keep adding questions if we want more questions than what's offered you're going to have to keep updating the template that's obviously not a great way to do it right so you have a couple of strategies here if you want to start abstracting out individual questions or questions themselves into their own component but believe it or not we can actually use a new feature of spelt called a snippet which allows you to essentially Define a reusable chunk of code directly inside of your spelt template and this could be seen as the way of in like a react component you just create a second function and you can use that as a component in your file this is that technique right so what we can do here is we can say pound just like we do any other template tag and we can say snippet and this is going to be a question and actually I'm going to
Snippets aka Inline Components
change it from question cuz I have a feeling sinking feeling I'm going to use that word we're going to say form step okay and form step is going to look like this we obviously need a closing snippet as well now each form step is going to look like what we had before but I think it's probably better off at this point to just type it out by hand so first and foremost we're going to have a wrapping div and actually let's wrap the whole thing even in an article article so each question here is going to have a div where we have a label and the four property is now going to be what could be considered the form ID like this and likewise the form label is going to be the question itself now these values don't exist yet but we will make them exist in a second and likewise we'll have an input and and the input is going to be the type of and check this
out we're just going to get to say this we're going to pass a type prop in here and that's going to define the type of the input the ID is going to be the ID like this and we're going to bind the value of this individual one into form step and then the ID itself now before we work on the incrementing or anything like that let's just get this working first so if we have this form step we can actually inside of this function put our props in here so question ID type okay and we can even give this typescript types as well so we can do colon and give these types if you would like if you're doing that type of thing and type you could say type is going to be whatever various form types you might have you could do that as uh string literals you could probably use an actual type for that but for Simplicity sake we're going to say string we're going to
say the type of ID is also a string and the question itself is going to be a string and I'm sorry I'm already seeing a typo I made I wrote form step here this should be form State we're accessing the form State itself not the form step which is the name of this snippet I was wondering why why that error looked so odd now I'm not going to bother with this type right now this is more of a typescript thing where it's expecting um you know an actual value within form State rather than a string here it it again it's not spelt related so we can fix that later but as you can see here we can type this just like any other function and just like kind of like how react works this is just a function that we can then run however the way that you run it which is with the at render which is typically used for rendering things like if you need to render an HTML string let's go ahead and and actually nuke out like all of this
code here and just get this going because you know what we don't need it we'll nuke out all of that and we'll say we're going to at render and then we're going to render the form step like this and the form step right now could just be considered a question with a what's your name ID of name and type of text okay and you can see this does render our form element really well obviously there's no next button it's not the exact thing we had but this is how a snippet works and you can see that that binding that we have even works across components because the snippet right here still has access to everything in this script so if you
define form State up in this script you then have also access to it within this snippet in addition you can pass in values into the snippet just like any typical function and utilize them in the Snippets code this is super handy for when you just need a quick each Loop and maybe you're just throwing things in a list item or something and you don't want to have that uh just sitting in your template for some reason it's just a really nice new feature and it's the type of thing where maybe you're just prototyping getting something going and then you might move this into a component of its own later with minimal effort okay so these are Snippets now before we get into looping over things to Output the snippet I want to show you something else with Snippets because it's a really great new feature and Snippets are how you render children inside of a spelt component because children ends up becoming an automatic snippet prop now you might not understand what I'm saying right now but let's show you here and I'm going to
Children Props
show you with the header and a typical component like this you'll have a self-closing component but not every component is like that and you can have um a closing component like this and you can pass something into it so hello whether or not this is just so you write a component as a wrapper as a very common technique or maybe it's a route there's a lot of reasons why you might do this but this is a very common technique in most frontend Frameworks to be able to pass in HTML inside of your component components this way to encapsulate it inside of your component now to do this and have this actually output in here we'll want to head to our header component and what's interesting is that spelt has a now built-in prop named children and the way you type this in typescript is by saying children is the type of snippet like this and this is an import that you have to do import type
snippet from spelt um I know a lot of people don't care about this typescript stuff but we want to have it anyways and likewise what we can do inside of our template tag is we can say at render children like this as if it's a function and you can actually pass things in this function and have it work just like a snippet does it's just a little bit more effort which brings us to the last snippet technique I want to show you really quick which is oh sorry we have a red squiggly I I wrote Chen um not a word children there we go fixed now this is going to bring me to the last snippet topic I want to hit before we get into Loops I know I keep putting that off but if we have an inline snippet where you do snippet like this and we can give this a name of
Inline Snippets
second child and this snippet of second child can look just like the snippet that that we had down below where you close it off with snippet and this snippet second child will be like second child like this now it's going to complain that this second child prop doesn't exist but I'll show you how we can get this going in the past and felt we use something called slots and a slot is a very common technique I don't know necessarily why they changed it to snippet I I think they probably just made snippet and decided hey um you know this is actually a very similar technique you know I can't say for certain that you didn't want to have multiple ways to do the same thing but this works just like this does the only difference is now that this has become a named slot a named child meaning that inside of our HTML see how this is accessed with render
children we could put this in an entirely different type of element here like we could put this if we really wanted 2 and an H3 and we can say at render second child like this now we have to make sure we add our second child to our props second child and then snippet second child sorry if I'm going fast I'm going to show you this in just a second move this all around okay so you can see that we have now typed our second child as a snippet we have second child coming in as a prop and we're able to pass second child into wherever we want in the Dom structure this means you can have various sections in the Dom do various different things if you want to have children going to multiple areas they're not just being plopped in in one spot these are essentially being turned into individual props that you can then render like this and again what's neat about this is that you can pass information upwards so the
second child's name is and I'll say Scott I am a second child so I'll just say Scott is the uh value that we're passing in here and then we can head to second child itself and believe it or not you have access to this value now second child [Music] name is Scott now typescript is going to be angry about this but again this is not a typescript course so uh the docs on how to get this fully typed are in these felt docs if that's the type of thing you want to know but it's very very interesting to know that you can pass information upwards from a component into a snippet just like you would in a render prop type of situation inside of react this is again is is maybe not a super common thing that you need to do but it does exist if you need to do it okay I'm going to go ahead and just undo a lot of what we just did with these Snippets this is a little bit of an
exploration into Snippets and I want to say it's a detour so I'm I apologize if you were excited to get into Loops but I'm going to go ahead and remove the second child and the the children from our props and just delete them entirely just so you can have that when you're looking in the docs it's under Snippets I just wanted to show you that was possible okay okay so let's get into our Loop stuff now actually so what we're going to have first and foremost is an array of questions and this can just be a const and I like an all uppercase true constant questions if you might if you don't like that then don't do it but basically we're just going to have an array full of questions we're in the same shape of the that we talked about before you're going to have a question value which is a string we can say what is your name you can always copy and paste these from the questions that we had written before um we can have an ID that ID is going to be of name and the type is going to be of text
Each Loops
okay before we add the birthday one let's go ahead and get this working with a loop because right now what we're doing is we're just rendering this snippet so if we want to Loop over an array you do pound each and then you do pound each the array name as the array value and if you wanted to add a key to this Loop like you do in react you do parentheses and then whatever the key may be so in this case it could be question. ID since we know that's going to be unique now the last thing we'll want to do here is we'll want to close out this each right and I think because I had an error I might need to refresh there we go you can see here what it's now doing is it's certainly only outputting our current form but it is going to Loop over all of the questions and output them with this render form step now we are hardcoding these so we can remove this what's your name but before I do that I want to show you something interesting that we can do as
well just like we have each questions asked question you could then output inside of here question. name and it will show you the question or we don't have a name property question. ID it will show you the value for question ID it shows up right here but we can also destructure values here so I'm going to keep this as a old version of this but I'm going to have the new destructured version right here and what we can do is destructure our object properties out of here so like ID question type and likewise we'll want to change this question. ID to just be ID so we've now been able to destructure each indiv idual property out of here and we're going to pass those in as question ID and type now this is the explicit way where you're showing exactly what's passed in here but uh bear with me here
as I show you uh a smoother way we could even do this further using what we had initially so if we go with what we had initially I'll duplicate this last line and then comment this out here uncomment this one and we can pass in the entirety of question in here like this now that only works in this particular instance where what we're passing into form step matches what we're grabbing from question one: one right um and many times you will find yourself destructuring properties outside of an age statement so both techniques are totally valid based on what you need I just wanted to show you that you could do either so we did mention that you could do a keyed block for this with an ID here or anything that's unique if you have an each Loop the reason why you want a keyed block is that it is so that the renderer understands exactly what is what here it gives it an ID for things now that doesn't necessarily mean you always need a key some people will say
always use a key but if I'm looping over let's say an array of strings in my header navigation and they do not change ever they're not interactive it's just outputting them to the Dom I don't really use a key there and I like that about spelt because that's not changing the Dom shouldn't care about that those things are just going to stay the same and therefore why do you need a key you know that just my personal Outlook again some people like keys on everything this should work just fine though I tend to do use keys with whatever I have inside of the array Loop ends up being dynamic in any sort of kind of way okay so now that we have each question output here let's go ahead and add our second question here to keep this rolling and we can say the second question is going to be what's your birthday it's going to be an ID of bday and it's going to be the type of text like this what's your name what's
your birthday pretty cool pretty cool you say Scott right here likewise so this is definitely working still again it's outputting both of them now we'll only want to Output them one at a time in just a second uh again we're just kind of taking things that piece by piece and we're not building the most effective app here but we're learning the techniques inside of spelt so you'll notice that this isn't very flexible right now this structure has to match this structure entirely but what if this structure changes and this one doesn't that's obviously you know I guess this structure wouldn't need to change but the properties here would need to change if for some reason they didn't match up one to one specifically like what we mentioned here you might not have noticed but we already have a bug in this where the ID is bday but the property value here is birthday right that's going to cause a problem so what do we do well we can make an answers value here and it's just going to be equal to an empty object we'll need a
comma there and now the way this is going to work in fact let's change this ID to birthday just to be explicit right so what is your name what is your birthday and instead of form state. name name here we can do form state. answers. name now name may or may not exist and right now it's going to say it doesn't exist but again this is going to be a typescript thing to unravel at the end of the day you would be getting the values of this ID field in some complex typescript to pass them in as the potential values inside of answer again not not something we're interested in spending too much time in on this course so that's one thing that we'll have to fix the next thing that we have to fix is is when we updated the individual form State now we can actually keep this largely the same if we do form state do answers and then ID you can see the site doesn't break here because what it's going to do is it's
going to create the property value of name or birth date inside of the form State and you can see as we type gosh this still all works now it works again because it's binding the form state. anwers and then we're passing the string of names or the string of birthday in here and then that's going to create that property if you want to see this in in action here we can always just for funsies we can do a jon.
stringify we can pass in form state in here again see how this is just a JavaScript expression here you can see the shape of our state right away so we can say Scott and then as we get our birthday which is currently not a the correct type of field we could say High okay um I'm wondering why it's not the correct type of field because we have type we have type we are passing in the type which means that I got the type wrong here it's a type of date there we go type of date date picker Scott look at that you can see how our object adjusts it's really pretty neat and that means when we actually go to submit this form all we have to do is look at form state. answers to get the answers for all of our form okay well this is really super good now this would be easy if you were having a form that was simply just a bunch of questions and then anytime
you added a new question for instance uh question what's your favorite color ID color and actually is there type of color I know there's a Color Picker let's try color check it out what's your favorite color yeah we got a Color Picker going okay and this all works really well where we now have an extendable form that allows us to add as many questions as we want but if we only want to show one form question at a time with a button that increments it what might we do well we can create a function here and this function can be next step what this next step function will we will do is simply accept an ID that's a string then it's going to look inside of if form state. answers and
then grab the ID to grab the right field if it is not equal to an empty string then we can do form state. step plus equals 1 again and again we can say form state. error just like we had all four is going to be cleared out into an empty string and we can also say else else is going to be form state. error is equal to please fill out the form input that's not really a userfriendly message but who cares okay so this right now obviously the UI is not using this next step function so let's add a button down here inside of our um we can actually end it inside of our snippet inside the article button onclick is equal to next step and
we'll say next and you'll see here that it's giving me some typescript error now this is actually saving us from a bug because it's saying that it's trying to pass in the event by default when you have an onclick event just like other JavaScript Frameworks if you don't specify a parameter and you pass in the function just like this the parameter that it actually gives you is the is the event so there you could do things like event. prevent default Etc but if we want to actually call this as a function and pass in a value you need to have an inline Arrow function this is pretty typical amongst JavaScript Frameworks and you may notice that this is bad logic here because if these values don't exist then it actually is going to pass because we're checking to see if it isn't equal to a negative string so you just want to check to make sure it's a truthy value so if this is a truthy value then you can go to the next step otherwise show the error now when we click this you can see that we do get the please fill out form input if we click any of them and the step is not
changing now we only want to show one at a time so we can do a simple if statement inside of our Loop so we have our each questions pound if if the form state. step is equal to the what well if we're thinking about this as a loop we would say like the index right if the index were're in the first one show the first one the second one show the second one but how do we get an index from our Loop well you get an index by saying comma I or index or whatever you would like some people just use I some people use index so we can say like so all right this is all pretty good now we are only having one question show up I click next gives us an error I fill out my name Scott I click next shows the next input likewise same thing with the error we can test all of these but what's so nice about this is it's repeatable okay and it sucked my
favorite color my favorite color is black then so be it okay so wow this is pretty cool now obviously we hit step four here and we're you know at a bit of a a state so let's go ahead and add some more conditionals just to make our form even nicer because now we care about this stuff so if form state doep is greater than or equal to questions. length then what we want to show is a thank you message right P thank you otherwise with an else show it like this so now I'm not going to go through this whole form or if I am I'm just going to do one clicks here there we go we're just trying to get to the thank you message boom thank thank you and it no longer shows the form now typically what you do in this situation is um you're listening for
this form function when you check the length and you're going to submit it and granted you would probably put the whole thing inside of a a real form anyways because really what we're just to changing as the display on a bunch of inputs but as you can see here we now have a really nice fully functioning form this is really pretty incredible and it works really super nice and if we were to clean up some of this code here it would all look in feel very nice so in the next part we're going to get into first life cycle and then animations because we're going to be able to animate this really easily with some built-in felt utilities that are that you should absolutely know out of the box and you probably are wondering about how to run code whether on Mount or when things change or for side effects again if you're the type of person who's coming from other Frameworks that's a use effect type of situation or maybe if even you're coming from older versions of spelt that's a dollar sign colon type of situation so we'll be talking about all that and more next if you need to take a break now's a good time to do so
before we get into the next section okay now we're going to get into the part where we learn about things like effect which are for people often say they're for something called side effects but I always found that to be so jargony because really it just means this code runs when something else happens now I guess side effect is fine for that but I think that can confuse some people about why these things exist so when something happens when some data has changed or perhaps the component is mounted or something like that this code will run okay now in previous versions of spelt you could have this reactive code working just by a simple dollar sign and then brackets like this and this was a pretty common pattern and it was a little confusing for people you could even do a reactive if statement by throwing an if in here in case in case you wanted to you know run this code
$effect & lifecycle
reactively uh if an if statement is conditionally true and in speld 5 we've kind of taken an approach that may feel sadly react likee but in reality is not now the only thing that is react like is the word effect because the way these things work is very similar to how these blocks worked inside of felt before but now we have dollar sign effect like this and what goes inside of an effect is a function typically done like this with an inline Arrow function now what typically goes inside of an effect is an inline Arrow function like this now what's interesting here is that this code by default will run on Mount so if we say console.log mounting or let's even just say unmounted now if I refresh this you can see this runs once and no matter what I
do to this this will not run again there's no reason for this to run again now part of what's interesting about spelt in general like we mentioned because it's a compiled we don't have to worry about running functions we can worry about values changing and how values changed but it also means we get to track if values changed so this by default is an unmount so after the component has loaded this code will run now what about out on unmount and to do this it's a return an arrow function here and this isn't just on unmount necessarily because one we're not even going to um unmount this component but but this right here will run one when unmounted or destroyed AKA this comp
this component has been removed either like an if statement a key block or anything like that then this is going to be run and it could also though run when an effect reruns so before the effect re runs because like an use effect in react or anything else this is not just an unmount this actually can track changes and listen for changes and then run some code whenever something changes so if we want to see that in action I'm going to have a second effect here we're going to say effect and again this takes a function like this and now instead of just console logging a string and having this run either when it's created or destroyed we're going to say console.log and we're going to say form State comma form
state. name actually there is no no name property I'm sorry form state. step okay so now each time the form step is run it's going to Output the form state so what's different about this verse this is that this is using a reactive value inside of here and this will rerun when form state. step has changed that's pretty amazing cuz in a react context you're passing in a second array full of the string values of the dependencies that will change inside of spelt because we're dealing with a compiler here spelt knows that hey we're using this variable and therefore if this variable should change then we need to rerun this function if we want to see this in action just watch the console down here I can even bump it up in size and clear it out so that way we can see
that yeah I'm typing nothing's happening but the moment I click next you can see that this function has rerun and likewise when I do it again it will rerun again and this can do anything you want it can listen for changes here and do this you can have this listen to any value and once that value changes it will then rerun and likewise what we said about the on destroy this will now run before the effect reruns so before form State rerun runs and reruns there we go and actually let's output the form state. step in here too just to see what happens right you might be very curious to see what happens let me clear this console let's start here I'm going to add my name I'm going to click next and when we click next you're going to see that before form State reruns it actually gets the current value of the step which is one and then the form
state is step is one so it's not giving you the before the state itself changes it's giving you before this function itself reruns now I don't end up using this that often unless it's something like um you know you create a set interval and you want to destroy it uh maybe for some particular reason maybe on component Mount or unmount these are the types of things like if you want a cleanup process you typically use this return function for a cleanup process now a lot of people like to make effect seem more scary than that and especially in react land I think it can feel more scary than that but really all you need to know is this thing will run when something has changed this thing will run when something has mounted or unmounted and you know this felt docs specifically even describe effect as an escape hatch it's useful for things like direct Dom manipulation but it's not a
tool that you should need to use frequently in fact the times that we needed reactive statements the most we're doing things like direct Dom manipulation via the audio player on this felt on the syntax website now the last thing we need to necessarily even talk about effect because I don't think we need to spend too much time on it other than this is how it works and when you need it reactive statement this is what you do but the thing that is important to know inside of these is that what you should not do is don't create State based off other state in effect we talked about this earlier on in this course when we used the derived Rune and that's when you're going to reach for derived so I'm just adding this simple note in here use derived if you ever have a state that relies or is based on another piece of state that's not a time to reach for an effect that's
time to derive your state from that you can go back and watch earlier in this video where we talk about that now I've covered a lot of stuff in this course and I still have some more things to cover but I do want to say if you go to the spelt 5 documentation you will see a lot of interesting ruins that we have not and will not discuss in this course things like effect. pre effect. traffing effect. root or even props do snapshot um there are additional runes inside of spelt that we have not that we will not be covering specifically because they are almost enti irely for advanced cases and you will not necessarily need to reach for them unless you do and because this is a beginner's course I want to keep this very beginner friendly now before we get into animations which is super fun and not something that's changed from spelt 4 to spelt 5 but something I feel like is definitely needs to be covered within a beginner's
Debugging With Inspect
course is the inspect Rune now inspect is a debugging Rune and it works like a log however it will update anytime a value reactive value has been updated so if we were to say form state.
step step right here you'll see something interesting and in fact let me even comment out the effects really quick down here so that way we don't get our form State logging a whole bunch clouding it up okay I'm going to refresh you can see that we have a new console log here and it says init zero which is interesting and what that's saying is is that this has run inspect has run once on initialization this value has been initialized to the value of zero and you'll see something very neat when we actually update our value so when we go to step number two it says update one which means that this will always run whenever this value has changed and it will always give you if it's been initialized or updated so that way you can tell if variables or reactive variables that you intended to write are actually updating or not or if they're updating too frequently uh for
some particular reason maybe you've written something where values are updating and they're not supposed to and so this becomes an incredibly handy tool I ended up writing a a quick little extension for this I believe it's called spelt wrap not warp wrap felt wrap it's right here um if if you would like to use this this this only has 13 downloads I I don't imagine a ton of people are using this but I use this all the time if I have a variable you can do this with a snippet too so you don't need an extension but if you have a variable something like questions right here you could have your mouse cursor on questions you could hit a keyboard shortcut default being command I and it automatically and it automatically gives you this inspect right here this ends up being super super useful anytime you have state variables youve just defined somewhere and you want to quickly inspect them you can move it here and then do do step to
get that value this is just a nice little shorthand by all no means you have to use this and uh judging by its 13 downloads I would imagine that not a lot of people are are dying to use this just yet so so just a small thing inspect is a really neat one that I felt like you should know okay okay okay now it's time to get into animations which this is a spelt I don't know going back X felt 3 feature this is a feature that's existed for spelt in a long time but maybe you're not used to working in a framework as full featured as felt is because they can add things like animations directly to the framework and not have it really blow the framework because we're compiling it right you don't have to ship this code if you don't want to uh but if you want these animations it's nice and easy so let's talk about how we might do this we can actually come down here to where we have our form step now anytime you end up having an if statement or other conditional blocks there's a block called key which we didn't talk about that changes if the key has
Animations
changed what you can do is you can wrap something in a div or an element here like so and on this you can give it the directive of transition and transition we could say something like transition fly and this is going to be equal to an object now inside of here you could give it how you want it to trans position you could say x is going to move over 200 pixels it's going to take a duration of 200 what is it 200 is a 200 milliseconds and then we're also going to change the opacity to zero as it happens now I have a full tutorial course on spelt animations themselves on syntax formally under level up tutorials so you can go check that out on level up. video but this is going to be all we need to have a simple animation now we do need to import fly it says we might have a name for if you do command period on vs code it asks you if you want to import it you can always just type this out as well
but that import looks a little something like this import fly from spelt transition now if I come in here enter my name here we go nice little swap now you will notice that they kind of pop in and pop out that's because there's no position absolu in going on you'd probably want to add some position absolute here or instead of just saying trans transtion in fly uh we can say transition in fly and we're going to go X is going to come 200 pixels duration and then opacity zero and then likewise we're going to say out fly X is going to be negative X is going to be -2 200 pixels duration will be 200 opacity will be zero okay let's try this out and see how this works so now one's going to come in One Direction and out the other who okay now we're still getting that
little that little blurb so let's add so let's add a delay of 200 pixels to the in that way we can tune the in to be different than the out so if we say Scott we're going to animate out first and then animate in two two Mill 200 milliseconds later check it out beautiful and this right here is out of the box endlessly awesome that this just exists this just exists with very little code now you could do it with transition and always throw a position absolute inside of a container on these that can get a little wonky another technique you can do is do a display grid and overlay them as a grid these are more or less animation problems more than spelts problems specifically cuz you're overlaying two elements on top of each other but if you're worried about a delay of 200 milliseconds here it's really as you could tell really Snappy
with what was going on here now in addition to fly there's a whole bunch of different transitions there's fade blur fly slide scale draw cross fade and there's a whole bunch of these that you can see taking place in examples on spelt dodev now I have no doubt that this site is going to look a little bit different once felt five drops so it's going to be a little bit different but these will all still be here now a little bit more advanced techniques that we get to in the spel animations course are things like speld animate where you can actually do flip transitions where it's first last invert play it's a really nice way of doing amazing transitions there's a whole easings package there's even something called spelt motion where you can have spring values that give you uh interpolated JavaScript string number values so that way you can do animations or really customly I mean the amount of stuff that you can do with this is pretty unreal now before we get out of here the last thing I want to show you is complex
Complex State
state within spelt now State can get more complex than this I'm just going to show you how you can create State outside of a spelt component and then create instances of that state within a spelt component we're not going to get too deep on this because I do believe this is a more intermediate technique but I do want to show that this exists now in spelt 5 one of the cool things you can do is use these runes and sort of this interact and this reactive State and things like that outside of a spelt component not something you could do before but you do have to use a spelt do TS or JS file so I'm going to create a quick state. spelt dots file okay inside of here I'm going to create a function which is create state I'm just keeping this very generic here and inside of create State we're going to have a new value value is going to be equal to state and this is going to be like a zero like
so and what we'll want to do is have a function which is just going to be named up so function up now I can't even spell up correctly All Right Now function up is just going to take the value and plus equals one to it okay so we're going to increment the value by one now last thing we're going to do is we're going to return out of here now in spelt 5 if you want to get the most recent value of your state you need to use something called a git function and this is going to be git value is going to return the most upto-date value that exists so when you call Value on the state that we end up creating which I'll show you in just a second you will then get access to the most upto-date version of value which
will in fact take into up or down or whatever you may have so we're returning essentially a state container that will have the value right here by a git function or in fact you can have a comma and then output the up function itself so this is our create state it gives me a red underline because it's never been used so let's export this I'm going to head into the header here because this is just kind of extraneous and I'm going to import create state from SL state. okay from here I can create a new custom State object here by saying const my state is equal to create state
and this now gives us access to doing things like let's put this in a button this is just kind of extraneous code here okay my state. value which is going to be zero you can see at zero right we're having to access this as a method or property using the git method here so if we say onclick we also exposed our my state. up function we can just call it like this so now whenever we click this my state that's inside of the state container will update okay so I hope this makes sense now what you cannot do from this now and you could using rables in spelt before we couldn't make a function that says my state value is equal to 10 right you
might want to update my state this way if we click this it's not going to let you it's going to give you an error so but this is actually possible using a set function so if we say set value like so all we have to do is say value is equal to and then the new value comes in as an argument new value like this and then we just need a comma Now if we click this we won't get an error it'll go straight to 10 we're able to set but but you need these Getters and Setters so what you can end up doing is you can end up building these really complex State wrappers with their own methods and what's nice about this is that you can expose the API that you would like to expose if I don't want users to handset the value if I only want them to be able to increment it then I only expose the up or down method or whatever I have here it gives you a
ton of control over how you write your state okay that's all really neat right but you might be like me and see these Getters and Setters and think man that's a lot of work that's a lot of work to do what we used to do with readable and writable those types of things if you use that in Feld or personally you might just see this and say this looks like a lot of extra code to just get a value right now I want to introduce you to a way of doing state that you might initially not feel super excited about but once you see the comparison I think you might be interested so I'm going to do export class and we're going to call this Scott State okay yeah that's right I'm going classes here and you'll see why in a second this pattern ends up being really nice first felt especially if you compare it to this one down here so if we say value and value is once again going to be a rune State like this where we give it a zero and then we also have our up
State with Classes
function defined like this as a method of a class we can then say this yeah that's right we're using this Value Plus equals 1 okay you could do plus plus two here if that's your thing okay let's go ahead and use this first before we really compare them but this is it seven lines of code then we head to our header we import Scott State we create const my state 2 is equal to new Scott State yeah we're using new these are class is right so this is what we have going here what we have cooking and now let's duplicate this however before we do that I'm actually going to return this to where we were just calling my value like this okay and we'll duplicate this we'll say my state 2. value my state 2 sorry this should be up and this should be up now one thing
you'll notice here is that all the typescript errors go away we have two buttons we click this one it works we click this one hey not so much what's interesting about this one is that we end up having to do a function where we call this
method um you can't just have it my state 2. up but you'll see that this now works exactly like this one works and we've now created state in two separate ways they both function the exact same the only major difference is really the how how concise they are authored right because this one yeah that's kind of a lot of code to just do what we just did but when you get into classes it feels really nice and what's cool about classes is you can have private values you can have public values you can have methods you can utilize The Constructor those types of things and this pattern ends up feeling really good in spelt a lot of the time so uh feel free to use classes to create more complex state if you'd like this is how you do it so that's it and this is about as advanced of a technique we're going to get into in this course now before we go I want to pop open the docs here and I want to talk about what we didn't cover because
What We Didnāt Cover
again these are the spelt 5 beta docs these will become the normal docs once it drops uh again this is this is just for me showing you what you aren't seeing in this course there are several runes we did not talk about there is a state. raw which will just give you Raw values that can't be mutated states.
snapshot takes an a static snapshot you could think of it as like something you might use for a deep clone um derived we talked about but we did not talk about derived by which is the same as derived but you get an inline Arrow function and you can do a little bit more so if the stuff that you're doing in derived can't be accomplished with just a single oneliner than you use derived by uh effect we mentioned effect. pre effect at all this stuff are not things that you're going to need to get into and mostly for Niche cases I'm scrolling through all this stuff these are the runes that we have not talked about so effect. pre runs before the Dom updates and it's not super common that you need that effect. tracking just gives you whether or not effect is currently tracking a value which I've seen people use this and I got to be honest I still don't get the uh use case it's one of those things that I'm sure I'll hit eventually but just to goes to show you that you can get a lot done without ever
needing things like this effect. root is an advanced rout that creates a non-tracked scope that doesn't Auto clean up this is useful for nested effects so this is getting into some really intense stuff likewise we talked about props and and type and typing props but we didn't talk about bindable now if you have a value that's being bound you saw that we used bind inside of input values when you have a prop that is bound to a child component so let's say you're binding a value in a child component and that value expect to change up the Dom tree up the spelt component tree like you update a value in a child component and you want it to change in the parent as well then you use in your props declaration bindable you use the prop name and then bindable bindable as a function so if you have a prop that needs to be changing uh in the parent you need to use this bindable as
well to have that work we did talk about inspect inspect is great now there's another one called host which retrieves the this reference of the custom element that contains this component but it's only available when you're using custom element components which in itself is not a common way to work in spelt now in addition we talked about Snippets we talked about naming Snippets maybe nested Snippets we talked about how to use them as children we did talk about event hand handers anytime you have an event whether that's on click on anything you now have it just be on the word okay so we typically see this and unclick now in addition there's also a bunch of intense fine grain reactivity State examples we did not talk about in case you want to get into some really intense State like we showed you how you can create dot State dosf felt State files and use State as a function or a class outside of a component that stuff is all exists but
there's more here there let me know what you want to see in an intermediate or Advanced version of this because now we definitely hit all of the beginner use cases for this but as we've been using spelt um I've been using it for a long time I built several major sites with it or even using spelt for the syntax site there are certainly a lot of use cases that you will hit over your time of working with this but I hope this was seen as a really good introduction and a good basis for the syntax maybe possibly the syntax changes of spel 5 stay up to date with syntax on YouTube we will be doing videos showing how we convert spelt four components to spelt 5 if you're coming from spelt 4 and want to see what that conversion looks like so as always this is Scott with syntax I hope you enjoyed this tutorial smash that subscribe button follow the syntax podcast anywhere you get your podcast and I will catch you in the next one
Quote it with credit and a link. Quoting Syntax