bus-tracker component page
Build a more complex component that combines the usage of <template>
and customElements
, and sets up event listeners.
Overview
In this part we will:
- Create another component named
bus-tracker
. - Display the
google-map-view
component within this new component.
Problem
We want to build a component that displays the CTA bus tracker routes and displays a map. This part builds the shell of the component and includes:
- A header with a title
- A placeholder for where the list of routes will go.
- The
google-map-view
component we created in the previous section.
How to Solve This Problem
- Create a template that contains the styles and markup for this new element.
- Create a custom element called
bus-tracker
. - Include the styles/markup in this element’s
shadowRoot
. - Place the
google-map-view
component within this new element’sfooter
.
Technical requirements
The styles for our bus-tracker
component should be contained within Shadow DOM. The CSS needed for the rest of the guide is:
The minimal markup needed for this component is:
The google-map-view
component should be displayed in the <footer>
section of the component.
What you need to know
To solve this problem you’ll need to:
- Know how to use CSS in a component that uses Shadow DOM.
- Use a component within another component.
Using styles within a component
Styles added to a page via <link rel=stylesheet>
cannot be used within a shadowRoot. Services like CodePen that allow you to add CSS will add them this way. Instead place your styles within a <style>
tag inside of the shadowRoot.
The :host
selector is a way to style the host of a shadowRoot
. A common use-case is to change the display. By default custom elements have a display of inline
which is like a <span>
. Often authors prefer to have a block
display, they can change this in their shadowRoot with this CSS:
In our component we are using display: flex
to give space to the header, route list, and Google map.
Nesting components
Any component defined using customElements.define()
can be used within another element’s shadowRoot
just as they can inside of the page’s HTML. To add the google-map-view
to this new component, place the tag within the footer.
Solution
✏️ Create a new component called bus-tracker
. Use the CSS and markup provided and place them in a <template>
with the id of #bt-template
. Create a shadowRoot for this element and append a clone of the template.