Using arrow functions in a Polymer or lit-element project is a simple and efficient way to write

I am currently exploring Polymer/lit-element and attempting to create a simple demo project. I have been trying to incorporate an ES6 arrow function within the class (specifically, the getButtonStyle function), but encountered the following error:

SyntaxError: This experimental syntax requires enabling the parser plugin: 'classProperties'

How can I properly use an arrow function in a lit-element project? What am I overlooking? Thank you for any guidance!

I have experimented with installing various Babel extension packages and configuring plugins in .babelrc, but without success (as it seems that it's not utilizing Babel). Additionally, I attempted to search online for solutions but did not find anyone facing the same issue.

import { html, LitElement } from "lit-element";

class ButtonDemo extends LitElement {
  constructor() {
    super();
    this.text = "Button";
    this.disabled = false;
    this.ready = false;
  }

  static get properties() {
    return {
      disabled: {
        type: Boolean
      },
      ready: {
        type: Boolean
      }
    };
  }

  getButtonStyle = (disabled, ready) => {
    if (!disabled) return "";

    var styles = "disabled ";
    styles += ready ? "saving" : "incomplete";
    return styles;
  };

  render() {
    return html`
      <style>
        button {
          //some style
        }
        button.disabled.saving {
          //some style
        }
        button.disabled.incomplete {
          //some style
        }
      </style>
      <button
        class="${this.getButtonStyle(this.disabled, this.ready)}"
        ?disabled="${this.disabled}"
      >
        My Button
      </button>
    `;
  }
}

window.customElements.define("button-demo", ButtonDemo);

Any insights or suggestions are welcome. Thank you.

Answer â„–1

When working with polymer, it is important to note that defining variables may require a different approach. For example, instead of directly defining them outside the constructor, you should move them into the constructor like this:

Check out a demo here

  static get properties() {
    return {
      disabled: {
        type: Boolean
      },
      ready: {
        type: Boolean
      },
      getButtonStyle: {
        type: Object
      }

    };
  }

constructor() {
    super();
    this.text = "Button";
    this.disabled = false;
    this.ready = false;
    this.getButtonStyle = (disabled, ready) => {
           if (!disabled) return "";

           var styles = "disabled ";
           styles += ready ? "saving" : "incomplete";
           return styles;
    };
  }

In testing scenarios, if you have defined disabled=false, the functions will return an empty string "". To see the styling effects, make sure to set disabled true.

Answer â„–2

To optimize your code, consider relocating the arrow function declaration to the module scope.

For example, you can move it like this:

getButtonStyle = (disabled, ready) => {
    if (!disabled) return "";

    var styles = "disabled ";
    styles += ready ? "saving" : "incomplete";
    return styles;
  };

By moving it out of the class declaration, you will be able to directly call it by name without using this.

Answer â„–3

This issue has no connection to lit-element at all. Unfortunately, not all browsers currently support this syntax, which is why you are receiving the babel warning.

However, Chrome 72 has already implemented this feature () so if you are using Chrome without babel, you can utilize it without any issues.

If you are using babel, you will need to install the corresponding syntax plugin as stated in the warning. There are many babel guides available that can assist you with this process.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Retrieving user information through an AJAX call

Looking for suggestions on how to modify my code to filter data retrieved from an API based on user input. Currently, the code fetches data from the API and populates a table. I want to create a function where the AJAX request only retrieves data that matc ...

Numerous unique identifiers dispersed throughout the element

There are multiple span elements with various ids like these: <span id="spn1" class="span-text">hello</span> <span id="spn2" class="span-text">world</span> <span id="spn3" class="span-text">12345</span> The issue aris ...

Using Javascript to Retrieve Object-Related Information from an Associative Array

I have a list of students' names along with the grades they achieved for the semester. How can I modify my JavaScript code to display the first names of students who earned an "A" grade based on the array provided? This is my current progress, but I k ...

Comparing defaultProps with the logical OR operator

Being relatively new to react, I’ve adopted a method of defining default values which looks like this: class TextInput extends Component { render() { return ( <input type="text" name={ this.pr ...

How can we replicate the 'setTimeout' feature in Node.js without causing any interruption to the event loop?

After extensive research, I have been trying to figure out how to implement non-blocking code in Node.js. However, all the examples I have come across are tied to functions that already have built-in callbacks. Therefore, I attempted to create my own funct ...

"Utilize jQuery to target textboxes that are positioned below others, rather than adjacent to them

My goal is to focus on textboxes that are arranged vertically, one below the other. However, when I write a query for pressing "Enter" to act as a tab key, the focus does not shift to the next adjacent textbox. Instead, I want the focus to move to the text ...

How can I access the '[native code]' using getAllResponseHeaders() in JavaScript?

Currently, I am making an AJAX call and trying to access the response headers. This is my code snippet: var xhr = new XMLHttpRequest; xhr.getAllResponseHeaders(); When I check the console, all I see is '[native code]'. Can anyone provide me ...

Tips for filling in the values for the options in a select dropdown menu

Currently, I am facing a strange bug related to the select element. Whenever I open the dropdown, there is always a mysterious black option at the top. This is how my HTML looks like: This particular element is part of my test controller. <select ng- ...

Apply a specific class to the input field when the name matches x

I have a website that loads a JavaScript file from a commercial service, so I am unable to customize this file. The output of this JavaScript file is a form with various input fields, all of which have the class name "wf-input". I now want to add a jQuery ...

The React setState function isn't updating the state as expected when used within the useEffect hook

I'm new to using hooks and I'm facing an issue with setState when trying to update data received from an API. Despite logging the response data successfully, it seems that the state does not update as expected. My useEffect function is set to run ...

Class is still visible after the media query preview is looked at, despite attempts

Our print preview library is set up to display the final product to users, but we don't want the images to actually be printed since we are using branded paper. To address this, I have included a print media query in the print.css file and added all ...

Utilizing Spaces in Parameters for discord.js

My current challenge involves sending tweets from discord.js. However, I encountered an issue where messages with spaces are being posted as "hello,from,discord" instead of "hello from discord". Can anyone help me rectify this? const Twitter = require(&apo ...

The Malihu jQuery Custom Scrollbar integrated with Meteor is failing to display on the webpage

I have successfully integrated Malihu's custom scrollbar into my meteor app using this package: The code I'm using is as follows: Template.post.rendered = function() { $('body').mCustomScrollbar({ theme: 'minimal-dar ...

The JavaScript function is facing an issue where it is not replacing the text accurately as anticipated when

I am currently working on a JS/JQ function that allows users to toggle between following and unfollowing a question. Depending on where the user clicks, they may encounter a link with text "Follow" or "Unfollow", or a button labeled "FOLLOW" or "UNFOLLOW ...

Jest came across a surprising token that it wasn't expecting while working with React and TypeScript in conjunction with Jest and React-testing-L

An unexpected token was encountered by Jest while using React and TypeScript along with Jest and React-testing-Library. Error occurred at: E:\Git\node_modules@mui\x-date-pickers\internals\demo\index.js:1 ({"Object." ...

Convert a JSON string into a formatted list categorized by type

I want to organize a JSON object into an unordered list arranged by Continent and then country. The JSON data is as follows: var mylocations = '{ "Locations":[ {"Place":"Africa_Egypt"}, {"Place":"Africa_SouthAfrica"}, {"P ...

What is the best way to ensure that a specific number of XHR callbacks have successfully completed before proceeding with further actions?

I have four requests that each have their own callback and can fire in any order. However, I need all the callbacks to finish successfully before executing mergeData. The issue with my current approach is that the initial parameter values do not refresh ...

Tips on utilizing spin.js in client-side scripts (Javascript and Node)

I've been attempting to utilize spin.js (!) from the client side, but unfortunately I have encountered some obstacles. I tried running npm install spin.js afterwards const Spinner = require('spin.js'); However, this approach was unsu ...

Generate an array containing 20 randomly generated math equations stored as objects using JavaScript

Reference Image My current task involves dynamically generating 20 math problems. These problems need to be stored as objects in an array before being displayed. I am facing a challenge in creating 20 unique random equations as objects and then calling th ...

The gap persists even when overflow is used in CSS

My HTML table is set up with an overflow property to ensure it doesn't exceed a specific height, but the following div is not being positioned directly below the scrolling table as intended. Even though I am using overflow: hidden, I can still select ...