Stencil js component why can't I access class variable from internal method?

337 Views Asked by At

Does anyone know why by searchButtonClicked() method prints undefined?

import { Component, h } from '@stencil/core';
import { faMagnifyingGlass, faX } from '@fortawesome/free-solid-svg-icons';

@Component({
  tag: 'search',
  styleUrl: 'search.scss',
  shadow: true,
})
export class Search {
  private searchText: string;

  handleSearchTextChanged(event) {
    this.searchText = event.target.value;
    console.log(event.target.value);
    console.log(this.searchText);
  }

  searchButtonClicked() {
    console.log(this.searchText);
  }

  render() {
    return (
      <div class="container">
        <h2>Find a Charity</h2>

        <div class="search-box">
          <svg xmlns="http://www.w3.org/2000/svg" class="icon" viewBox="0 0 512 512">
            <path d={faMagnifyingGlass.icon[4].toString()} />
          </svg>

          <input type="text" placeholder="Search" onInput={(event) => this.handleSearchTextChanged(event)}/>

          <svg xmlns="http://www.w3.org/2000/svg" class="icon" viewBox="0 0 512 512">
            <path d={faX.icon[4].toString()} />
          </svg>
        </div>

        <button onClick={this.searchButtonClicked}>Search</button>
      </div>
    );
  }
}

1

There are 1 best solutions below

2
Ali Hejazi On

Never mind, I figured out the reason. I had to update the onClick definition to the following:

onClick={() => this.searchButtonClicked()}