Creating Web Components with Stencil

Creating Web Components with Stencil

What is a Stencil ?

Stencil is a developer-focused toolchain for building reusable, scalable component libraries and design systems. It provides a compiler that generates highly optimized Web Components, and combines the best concepts of the most popular frameworks into a simple build-time tool.

If you ever worked with angular/typescript then It will be very easy for you to learn stencil,
because most of the syntax are same.

My First Component

Stencil components are created by adding a new file with a .tsx extension, such as my-first-component.tsx, and placing them in the src/components directory. The .tsx extension is required since Stencil components are built using JSX and TypeScript.

Example :

import { Component, Prop, h } from '@stencil/core'; @Component({ tag: 'my-first-component', }) export class MyComponent { // Indicate that name should be a public property on the component @Prop() name: string; render(){ return ( <p> My name is {} </p> ); } }

Did you notice the syntax?

It’s similar to angular, right!

Now, Let’s understand it,

Once compiled, this component can be used in HTML just like any other tag.

<my-first-component name="Elite-Corner"></my-first-component>

When rendered, the browser will display My name is Elite-Corner.

So what is really going on here?

Let’s dive in.

The First basic thing is @Component() decorator, It provides metadata about components, Like which tag name to use and which file to use for the styling that component.

Below the @Component() decorator, we have a standard JavaScript class. This is where you’ll write the bulk of your code to bring your Stencil component to life. Here is where you’d write functions or provide business logic.

In order for the component to render something to the screen, we must declare a render function that returns JSX. If you’re not sure what JSX is, don’t worry, we’ll go over it in detail in the Templating Docs.

The quick idea is that our render function needs to return a representation of the HTML we want to push to the DOM.

The name property on the class also has a decorator applied to it, @Prop(). This decorator tells the compiler that the property is public to the component, and the user should be setting it. We set this property like so:

<my-first-component name="Elite-Corner"></my-first-component>

Any property decorated with @Prop() is also automatically watched for changes. If a user of our component were to change the element’s name property, our component would fire its render function again, updating the displayed content.

Thanks for reading this articles, stay tune for more articles. 🙂

Also Read :