How to Build the Reusable Web Components Using Stenciljs

April 23, 2018 0 Comments

How to Build the Reusable Web Components Using Stenciljs



Stenciljs is a Compiler Helps us to build Web Components and use everywhere in Your JavaScript Projects(Angular, React, Vue) without a need to copying onething again and again.You can either use

it in your vanilla JavaScript.

Stenciljs uses the syntax which is a combination of the jsx and typescript We called it as tsx.

Let's Build a web component Using Stencils

Open Your Terminal and clone it from GitHub

git clone my-header 
cd my-header
git remote rm origin npm install

after running npm install all dependencies installed

now run npm start to power up the server 

Open the project in your favorite code editor



  • Open your src folder it shows the components Folder

  • Delete everything in the components folder

  • Let’s build a new component from the scratch

Add the new folder named my-header in the components folder

In the my-header folder

create two files show in the below image

Now open my-header.tsx file and add the below code

Let us talk about what these code is doing

1). At line one we are importing the Component decorator and Prop decorator from the stencil core.

2). Next, we want to config the name of the component and CSS URL.

tag: "my-header",
styleUrl: "my-header.css",
shadow: true

3). We already discussed stencil is the combination of the jsx and typescript.In react we are writing props using the {props.first} but in the stenciljs we use it with Prop decorator.

4). So that we want to tell the stenciljsi want to use these props in the my-header component.

@Prop() first: string; //type string 
@Prop() second: string; @Prop() third: string;

5). Let us get to the render method we already saw it in the reactjs
in the render method, we can write HTML and javascript combination

we need to return the jsx same as react.

render() { 
return (
<header> <nav> <li>{this.first}</li> <li>{this.second}</li> <li>{this.third}</li> </nav> </header> );}

We are referencing to the props using this.Propname

Now let's add the little bit of CSS in our CSS file already created

Now the final step we want to add our component in the HTML file

we added props to the HTML file we already defined in our my-header component


It looks like these

Thanks for spending your valuable time..

Let's discuss in the next post how to use this component in the React, Vue and Vanilla JavaScript

How to use Stencil components in Angular apps

Code Repository


Tag cloud