Search code examples
javascriptreactjsangularstenciljsstencil-component

Why My Stencil count button doesn't refresh the page?


I'm new in Stencil.js, but I have experience with React. My first ejercise in Stencil doesn't work. I tried to make a simple count buttom. The result is that: enter image description here

The var contador is NaN and the number 0 is always 0.

Code Component:

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

@Component({
  tag: 'my-component',
  styleUrl: 'my-component.css',
  shadow: true,
})
export class MyComponent {
 

  
  @State() contador = 0;


  contar(){
      this.contador++
      console.log (this.contador);
    }


  render() {
    return (
      <div>
        <button onClick={this.contar}> <span class="menu-icon">CONTAR</span></button>
          <nav class="navigation">
            <ul>
              <li><a href="#" class="logo">{this.contador}</a></li>
            </ul>
          </nav>
      </div>
    );
  }
}

Index.html code

<!DOCTYPE html>
<html dir="ltr" lang="en">
  <head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0, minimum-scale=1.0, maximum-scale=5.0" />
    <title>Stencil Component Starter</title>

    <script type="module" src="/build/cosmoprueba.esm.js"></script>
    <script nomodule src="/build/cosmoprueba.js"></script>
  </head>
  <body>
    <my-component></my-component>
  </body>
</html>

I was watch this video as walkthrough https://www.youtube.com/watch?v=jm45n5bh2Ak&t=2s

The body doesn't "refresh", it remains at 0 always. I tried another exercises, for example, hidding a text with a button, the result is the same, don't refresh.

I have the last version of node and npm: npm: '9.5.0', node: '18.14.2',


Solution

  • The click event handler automatically binds this to the element triggering the event. In order to avoid this implicing this binding, you can switch to an arrow function which will avoid the binding to the element object and keep a reference to the Component instance.

    Try using an arrow function:

      contar = ()=>{
          this.contador++
          console.log (this.contador);
        }