Web Components Crash Course

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
[Music] hey what's going on guys welcome to my web components crash course so front-end web development is a pretty congested area of technologies we have all types of frameworks and libraries and tools but one common theme is delivering high quality user interfaces with encapsulated components so when you use a framework like react or view or angular or just about any other front-end framework you break everything up into components everything in your UI whether it's a search bar a head or a blog post whatever it might be well we can actually do something similar without even using a framework and without the risk of it becoming obsolete and that's by using web components so in this crash course we'll talk about what web components are we're going to look at a couple slides and then we'll jump in and I'll give you an example on how to create a web component from scratch we're going to create a user card web component so let's talk about what web components are they're essentially a set of web app web platform api's that allow us to create custom reusable and encapsulated HTML tags that we can use in web pages and web apps so if you've ever used a front-end framework again like react or view one of the main advantages is having an organized UI of components if you have a header component that includes the mark-up or the output it includes the styling and any JavaScript functionality that comes with it and you can simply embed it on the page so web components work in a similar way and we don't need to install any kind of third-party framework or library or anything like that it can all be done with vanilla JavaScript but of course you can easily integrate web components with something like react if you want to now this three main building blocks when it comes to web components we have custom elements the shadow DOM and HTML templates so these all work together you can use them use them individually but for the most part when you create web components you're going to be using all three so I just want to go over all three and just kind of explain what they are so first off custom elements they give us the capability to create our own custom HTML tags just like you have a header aggghhhhh footer paragraph we can create completely custom tags as well we can also we can actually extend HTML tags as well so this is done by creating a class within our JavaScript that extends this HTML element you can also extend existing elements like say HTML paragraph element but we're not going to really get into that we're gonna create our own custom ones so this is an example this app draw class and the way that we basically bind this to a custom tag like this is by using this custom elements dot define and then whatever we want to call the tag ok the convention is - so if you want to have any you know if you want separate words like this you want to use a hyphen and then just connect it to our class and this class can have a constructor with lifecycle methods as well so I just want to quickly go over some of those lifecycle methods that are available to us so we have a constructor which is very common in object-oriented programming it's basically called right away whenever and there's an instance of the element that is created or upgraded and for in the constructor you would do things like initialize any state you have event listeners things like that and then we have connected callback which is called every time the element is inserted into the DOM and then disconnected callback is called every time it's removed from the Dom so if you want to remove any event listeners or anything you would do it here we also have attribute changed callback which takes in whatever the attribute name is the old value and the new value so this is called when an attribute is either added removed updated or player replaced because when we have a custom tag or custom element we can actually pass in custom attributes much like we would props in something like react so the shadow Dom is it's basically self containment it allows us to encapsulate all of our markup and our styles in our custom element so it's basically its own entity apart from the you know the regular Dom the document object model so the styling is separate from the global CSS of the web page so if we have like an h3 inside of our web component and have it styled a certain way that style is gonna stick and if there's any global styles on the webpage it's not gonna affect our h3 or whatever whatever element that we're talking about okay so we have scope styles we create the shadow Dom inside of the class by using whatever our custom element is and then using this attached shadow method and for the most part we add this mode open so that we have access to the shadow Dom within for instance our our chrome dev tools or whatever browser dev tools you're using and this creates a what's called a shadow root that we can actually reference throughout our class and we can interact with all right and if this sounds confusing don't worry about it I'm going to show you exactly how to do this so we also have HTML templates this is how we define the encapsulated markup of our web components on page load the template tag allows us to store some markup on the page you can later clone and reuse so we can include both HTML and CSS in our template we can also make use of something called slots which allow us to make the template dynamic and add output to it or add custom text to it okay so now I mean that's it for the slide so I want to jump in and just show you what makes up a web component we're gonna look at creating custom elements the shadow DOM and HTML templates okay so we're gonna start working with web components what I have here is just an index.html and a user card dot je s the user card je s is completely empty and in the index.html I just have some basic markup I have an h3 and then a script with the source of user card je s so what I would like to do here is create a user card web component so I want to be able to actually have user card like this okay and have that output whatever I want really in in this case it's going to be an avatar a user image a name phone and email and also a button to show and hide the phone and email okay so just just so I can give you an example of having an event and some interactivity so let's go ahead and save this and obviously nothing is gonna happen here I mean this is not an actual HTML tag so we want to go into our user card j/s and the first thing that we want to do here is create a class okay just like I showed you in the in the slides so we're gonna call this user card and we want to make sure we extend HTML element okay so what we're doing here is creating a custom element and inside here we're going to have a constructor which is just going to run right away and we need to call the constructor of this class that we're extending and we do that with the super method okay so we want to call that and then we can use the this keyword to pertain to our custom element and what I'm going to do is just insert some HTML so we'll just set this actually let's set this to some backticks and for now I'll just say John Doe okay you know if I save this nothing's going to happen because all we've done is created the class we haven't actually defined the custom element to do that we want to take on the window object we have custom elements and then we have a method called define and this is going to take in two things it's going to take in the name of the tag so user card and then the class that we want to connect it to which is the user card class we just created and once I save you'll see that it outputs John Doe on the screen okay so I mean that that's the the the basics of creating a custom element we have custom tag we have this class with a constructor all we've done is set the inner HTML and we've defined it here all right now let's say we want to pass in an attribute like a name for each user because obviously each user is not going to have the same name so the way that we can access this and here and we're not dealing with the shadow Dom or templates or anything just yet I'm just this is just custom L custom elements so in here let's go ahead and since we use back ticks we can use a template literal we can use this syntax and let's say this dot get attribute ok this pertaining to our custom element and we want to get the attribute of name and save and now it still says John Doe if I change it to John does and save we get John does and we can create multiple cards so if I want to create another one here with let's say Jane Doe and save now we get Jane Doe alright just like if you were to create a component with with a framework now as far as styling goes right now let's add a global style for what is h3 did I make it an h3 no I didn't let's actually make this an h3 ok so we just added an h3 there and then in the global Styles I'm gonna say h3 color and we'll set this to purple and save and notice that both h3 is a purple this h3 that's directly in the Dom and well I mean this is still directly in the Dom for now but in our custom element our h3 is also purple now what we could do is in here we can say style and we could set h3 color to say coral and save and it does turn coral but so does the h3 that's outside of it and we don't want to do that we want to encapsulate everything into a web component so to do that we're gonna create a shadow Dom and the way we do that is in the constructor let's go right here and we'll say this pertaining to our custom element and then attach shadow ok I showed you this in the slide so a tat shadow and we just want to set some options with mode and set that to open all right now once I save that this it actually disappears because our shadow dog this isn't how we handle things using the shadow Dom we need to first of all use our shadow root and we're going to append sorry appendchild so we're gonna add into our shadow root our template which we haven't created yet but we will so we're gonna say templates dot content dot clone clone node and just pass in true here so this returns a copy of a node if deep is true the copy also includes the nodes descendants so we need to create this template right here so right now let's just set that to nothing for now and let's create our template because right now it's just gonna give us an error because it doesn't know what this template is so I'm gonna go above the class here and let's say Const template and we're gonna use document dot create element which does just that it's going to create a new element of template okay and then what we'll do is take our template and set the inner HTML to whatever we want so be sure to use back text here and let's add in style and let's set our h3 style color to coral alright now in addition to styling we want our markup here as well so I'm gonna have a div and I'm gonna give this a class of user card because I do want to style it you know somewhat nicely so we'll have a div with user card and then let's have our h3 here now remember down here I had this dot get attribute dot H to get attribute and then the name right well I can't do that here like I can't do this dot get attribute cuz it doesn't know what this is I'm not inside the class anymore so we're actually going to just leave this blank and we're gonna deal with it down here so let's see so far we have we've added the templates so now I'm going to take the shadow root because from now on this is what we want to use to select stuff from our custom element or from I should say our web component so we're going to use query selector and we're gonna select the h3 and let's set the inner text and then set that to this to what we had before this dot get attribute and we want the name attribute all right and then we don't even need to do this anymore because we are working with our template okay working with our template and we're working with our shadow Dom shadow root so now if I save notice that John Doe is back on the page and it's coral and then this hello world is purple okay so the styling that we have in our template here and our web component is only going to affect our web component it doesn't affect the outside and the outside doesn't affect our web component and also if I open up my chrome dev tools and let's just inspect this so we can see the h3 and then it'll show us our user card web component with the shadow root okay and inside the shadow root is our h3 there are style tags and then we have our div with our h3 okay so another thing that I would like to do is pass in an attribute for an avatar or an image so in our user card here because you can have as many attributes as you want let's pass in avatar and I'm just gonna set this to I'm gonna use random user dot me so if we say random user dot me slash API slash portrait slash men slash one dot jpg that should give us an image so we're passing in a URL or it could be you know a local image and then what we want to do is same thing we did with name I'm gonna go just grab this here except let's see we want query selector we're gonna select the image and I'm not setting the inner text I'm gonna set the source to the attribute of avatar now it's not going to show yet because in our template we don't have an image tag so I actually want to format this as let's say we're gonna have a div here that wraps around let's move this h3 so I want to have the h3 inside of a div and let's see above that div we're gonna have an image tag okay so we have our main let me just indent this so we have our main user card div and then an image and then a div with an h3 and the reason I put a div is because I'm also gonna have some other stuff down here after but let's go ahead and save this and now you can see we have our image okay if I want another user card I could take this copy it down and let's change let's see we'll change this to portraits woman and let's say Jane Doe and if I save now we have another user card component okay with a different avatar and a different name now before we do anything else here I want to finish up finish up our templates so that includes some styling as well as adding to our markup so as far as the markup goes all I want to have is under the h3 I'm gonna have a div with the class of info and inside here I just basically just want to have the the email and the phone number of the of the the user so for now I'm just gonna put in I guess a placeholder will just say email and phone cuz I'm gonna show you how to use slots in a little bit and then under that I'm also gonna have a button because I do want to show you how we can have some interactivity we can have events I'm just gonna have a button to basically toggle that info so let's give this an ID of toggle info and I'll just say let's say hide info so we'll add some JavaScript to change the text as well to hide and show so if I save that we just have you know our paragraphs here and then our button now I do want to add some styling so I don't want to type all the CSS out because I think you know that's not the focus of this course so I'm gonna just paste this in and just quickly go over it it's not much so basically the user card we're just added you know adding a font family a gray background we're setting the width to 500 we're going to use the grid so that the image you can see the image is going to be one grid item and then this told div with everything else will be another grid item and we're just setting it to have two columns one is one fractional the the image and then the text part will be bigger it'll be two fractions okay grid gap just add some margin bottom border bottom the image is a hundred percent and then we're just styling the button making it this dark orchid color and border radius and so on so I'm gonna go ahead and save this and this is what its gonna look like this is actually zoomed in let me put this back to 100% okay now I want to show you how we can use slots to add this the email and phone or add anything we want so within our user card here let's just go to this first one here and let's just put in anything we'll just say hello okay now this isn't going to show anywhere in here but if I go to my template and in this paragraph right here I'm gonna use slot like this and save and now you'll see that it says hello just for the first one because that's the only one that we that we dealt with in fact let me just comment that out for now so if you just have one thing that you want to put inside here you can just put whatever you want and then just use slot now we have two things that we want to add we want to add an email and a phone so what we can do is inside here instead of just putting hello or whatever an email we're gonna add a div and we're gonna give it a slot attribute okay and in this slot attribute we're gonna say email and then we'll pass in some email let's say John Doe @ gmail.com now I also want to have a phone so I'm gonna copy this down and this is gonna be our phone slot so let's do that and let's change this to phone okay now if I save that you'll see that it's not going to show here just yet what we need to do is add to this slot here we can add a name and this is where we want to put the email and then here this is where we want to put the phone so now if I save you'll see the email and phone okay and then for this user card here let's go ahead and uncomment that and let's say we want to put inside here I'll say Jane Doe and I guess we'll just change this okay so now we'll save and now Jane Doe has a different email and phone number all right so this is all self-contained this is all everything is in the shadow Dom in the template now the last thing that I want to show you that I want to add to this is some events or an event I want to be able to hide this info by clicking this button and you can have whatever functionality you want if you want to add some cool animations or just absolutely anything you can put in your your web component I just wanted to give you a pretty simple example now this button here has an ID of toggle info right so we're gonna need to have an event listener on that button and we're I'm gonna put that event listener is in a life cycle method called connected callback remember that from the slides it's basically called every time the element is inserted into the Dom so under the constructor let's say connected callback which is kind of a weird name for it but we're gonna take the shadow root because remember that's what we're working with here and we're gonna use the query selector and we want to grab the ID of toggle there's a toggle dash info and we want to add an event listener onto that and we're gonna listen for a click and once that happens we'll have an arrow and then we're gonna call this dot toggle info all right so it's a really nice way to just encapsulate everything and have it nice and neat so this toggle info we can create within our class so let's actually put that right here so toggle info and for now let's just do a console log 1 2 3 just to make sure this works so I'm gonna open up my dev tools and go to console and if I click this we get 1 2 3 ok so we know that that is hooked up now as far as removing the eventlistener we can do that in disconnected call back so in here let's say I guess I'll just yeah we'll just copy this and let's see we're gonna say query selector toggle info and then we just want to call for a move event listener like that so that way if it's taken out of the Dom it'll remove that event listener all right now in toggle info like I said I want to be able to click this and basically toggle the info also change the text of this to high tide info to show info and so on so I mean there's there's a lot of ways you could do this I'm actually going to set a property up here call the show info and set that to true by default because we wanted to show you want this to show by default and then inside toggle info we can access that so this dot show info and we're gonna set it to whatever it's not so this dot show info and then let's say if if this dot show info else okay so we just basically want to change the display to hidden if it's if we don't want to show this and we also want to change the text so I'm gonna actually grab the the two elements we have a class of info right which is wrapped around the email on the phone and then of course we have our toggle info ID for the button so let's let's put those in variables just to make it a little neater so we'll say Const info equals this dot shadow root let's actually close that up shadow root dots query selector and we're gonna grab the class of info all right and then we also want to grab the ID of toggle info so the button and we'll call this toggle BTN okay so if this dot show info then let's take info and just set the style of display info dot style dot why is it doing that dot display and we want to set that to block because we're showing it okay and then we also want to change the button text so we'll take the toggle button and just set the inner text to hide info because at this point it's showing display is set to block so it's showing so we want this to say hide info which is its default state and then else let's change this to none and let's change the text to show info okay so we'll save that we'll go over here and if I click hide info it hides the info it sets it to none right and it also changes the text to show info and if I click it again it shows it okay and we can of course have this one open this one closed and we can have as many web as many of these use your card web components as we want alright guys sorry I mean I know this isn't the most advanced these aren't the most advanced web components obviously we could do a lot more here but this is a crash course this is an introductory to web components I'm just gonna get rid of this hello world we don't need that anymore and we can also get rid of this style here I just wanted to kind of show you the encapsulation of the the shadow Dom but anyways I mean yeah so hopefully you learned something here you can create your custom elements you can pass in attributes and you can use these slots to add content inside you know create your class your template attach the shadow Dom append the cha append the template and then whenever you want to reference your web component you reference the shadow root you can select whatever you want from the template and and just you can do whatever you want it's just a nice way to organize everything and of course you have these callbacks or these lifecycle methods that you can use if you wanted to fetch data maybe you have a web component that fetches data from some kind of API or some kind of back-end you can do that in you know the constructor or connected callback or whatever then you can fetch data so I would encourage you to come up with some ideas experiment with it build your own style for your own web web components and and that's it thanks for watching and I'll see you next time
Info
Channel: Traversy Media
Views: 150,244
Rating: 4.9635048 out of 5
Keywords: web components, custom elements, html elements, shadow dom, javascript
Id: PCWaFLy3VUo
Channel Id: undefined
Length: 28min 54sec (1734 seconds)
Published: Tue Mar 17 2020
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.