Nested Stencil components

In the last section, we looked into the @Component decorator and how it helps create a Stencil component. In this section, we will use one more decorator called the @Prop decorator to declare the variables that will act as properties which can be passed onto other components. 

Let's create an element that shows us a list of students, called <student-list>. In Stencil, it would look something like this:

import { Component, h } from '@stencil/core';

@Component({
tag: 'student-list',
styleUrl: 'student-list.css',
shadow: true
})

export class StudentList {
render() {
return <div>
<div>Student List is as follows: </div>
<student-name class="student-list__student" first="John" last="Doe"></student-name>
<student-name class="student-list__student" first="Tom" last="Hanks"></student-name>
</div>;
}
}

Here, we are doing the same thing as we have done in the <hello-world> component. We are simply importing the stencil library, then setting the name of the component and CSS styles in the @Component decorator. And, in the class, we have a component called <student-name> that has the first and last name as attributes.

Let's take a look at the definition of this <student-name> component:

import { Component, Prop, h } from '@stencil/core';

@Component({
tag: 'student-name',
styleUrl: 'student-name.css',
shadow: true
})

export class StudentName {
@Prop({reflectToAttr: true}) first: string;
@Prop() last: string;

private getFullName(): string {
return `${this.first} ${this.last}`;
}

render() {
return <div>Student Name: {this.getFullName()}</div>;
}
}

Here, if we look inside the StudentName class, we can see that we are using the @Prop decorator. With the help of this @Prop decorator, we are defining two properties: first and last. The first property also has reflectToAttr set to true, which means that this property can be seen as an attribute when it gets called inside the <student-list> component:

Here, we can see the attribute first in the shadow DOM for this component. But since we did not set reflectToAttr to true for the last property, it doesn't get reflected in the attribute.

Also, if you notice the definition of the <student-list> component, we did not import the <student-name> component. We simply started using the element. Stencil is smart enough to pick up these changes and auto-include them in the files. This way, we can create nested elements without worrying about the imports.

Now that we know how to create nested components using Stencil, let's look at one of the ways to achieve performance on to the web page we are trying to create.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.129.216.7