How to use TypeScript to modify button styling with an OnClick() event handler

Learning TypeScript with Existing Code Transition

Currently, I am delving into the world of TypeScript and in the process of converting my CoffeeScript code to TypeScript (specifically Lit Web Component).

Confusion on Translation Process

I'm encountering an obstacle in understanding how this particular line should be converted to TypeScript:

render: ->
  className = if (@props.firstProp) in @props.secondProp then "buttons buttons-active" else "buttons"

This code snippet essentially adjusts the appearance of a toggle button. When a specific property exists, it triggers a custom button class and upon clicking, applies the active styling.

Desired Outcome

My goal is to click on the switch and alter its CSS styling while also toggling the condition between true and false. If the condition is true, apply the

container-style-light button button-active
style; upon clicking again, revert back to false and restore the styling to just container-style-light button.

    @customElement('toggle-button')
    export class ToggleButton extends ElementLit {
      static styles = css`
      button { border-width: 1px;
        border-style: solid;
        width: 50px;
        min-width: 50px;
        height: 50px;
        border-radius: 25px;
        font-size: 0.9rem;
        margin: 0;
        padding: 0;    
    }container-style-light button {
      border-color: var(--highlight);
      color: var(--highlight);
      background-color: var(--background);
    }
    container-style-light button button-active {
      background-color: var(--highlight);
      color: var(--foreground);
    }   

    @property()   
    condition = true;

  constructor() {        
    super();
    this.disabled = false;
    this.displayName = `${this.condition}`   
}

 render() {
    return html`
    <style>${ToggleButton.styles}</style>
    <label>
      <button type="button" 
      ?disabled="${this.disabled}"
      @click=${this.onClick}>
      ${this.displayName}
      </button>
    </label>`;
  }

    
      private onClick(_e: Event) {
       //change the styling of the .button to button-active, set condition to true
      //if clicked on again, revert to the .button styling, set condition to false
    }     
 }

I would appreciate guidance on the simplest method to accomplish this in TypeScript, as there are multiple components awaiting translation.

Answer №1

Create an object named classes with the button_active property set to a boolean value. Utilize the classMap directive to associate these classes with the btn element and toggle them upon clicking the button.

 const classes = {
  button_active: this.toggleBtnState;
 }

 private onClick(_e: Event) {
    this.toggleBtnState = !this.toggleBtnState
 }     

render() {
    return html`
    <style>${ToggleButton.styles}</style>
    <label>
      <button type="button" 
      ?disabled="${this.disabled}"
      @click=${this.onClick}>
      ${this.displayName}
      ${classMap(classes)}
      </button>
    </label>`;
  }

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

Creating a legitimate Angular 6 form模shape

I want to reset my form using the following method: public static resetDescriptionFields(i: any, component: any) { var formItems = component.form.get('items') as FormArray; var descriptionItem = formItems.controls[i].g ...

Iterating through an SVG path multiple times

If I have the arrow below and I want to place it at various locations within the svg: <svg width="400" height="400"> <path transform="translate(150,100)" fill="black" d="M 0.5,0.5 l-100,0 -25,20 25,20 100,0 z" /> <path transform="translate( ...

What is the solution for the error stating "Unable to locate a declaration file for the module 'request-context'."?

I am currently working on three different files: index.js, index.main.js, and app.js. My goal is to use request-context to extract a variable from index.main.js and pass it to index.js. Within my app.js file, located in the server folder, I have the follo ...

Styling the CSS tables with alternating row styles for rows 1 and 2, followed by a different style for rows 3 and 4. This pattern will repeat

I've been struggling to create a CSS table style using tr:nth-child to alternate row colors: Row 1 - Blue Row 2 - Blue Row 3 - White Row 4 - White ... and so on. I can't seem to get it right! Can anyone help me out with this? Appreciate an ...

The type FormGroup<any> lacks the controls and registerControl properties compared to AbstractControl<any>

I've been developing a reactive nested form inspired by this YouTube tutorial - https://www.youtube.com/watch?v=DEuTcG8DxUI Overall, everything is working fine, except for the following error - https://i.sstatic.net/bZHPV.png Below are my files. ho ...

Modify the Primevue Class p-accordion-header only under certain conditions

I'm currently facing a challenge with customizing the styling of the primevue component class p-accordion-header based on the status of the rendered component determined by the variantNumber. Here's a snippet of my code: <Accordion :multiple= ...

Deploy the Angular standalone component numerous times across a single page using Bootstrap

Edit After receiving input from Andrew, I have decided to adjust my strategy: Replacing survey-angular with the survey-angular-ui package Implementing a widget approach similar to the one outlined in this example Developing a single module that encompass ...

Issues arise when trying to update the modelValue in unit tests for Vue3 Composition API

Recently delving into Vue, I am currently engaged in writing unit tests for a search component incorporated in my project. Basically, when the user inputs text in the search field, a small X icon emerges on the right side of the input box. Clicking this X ...

What is the best way to ensure that all function parameters using a shared generic tuple type have a consistent length?

Understanding that [number, number] | [number] is an extension of [number, ...number[]] is logical, but I'm curious if there's a method to enforce the length of tuples based on the initial parameter so that the second tuple must match that same l ...

Attribute specified does not belong to type 'DetailedHTMLProps<ButtonHTMLAttributes

I am working on creating a reusable 'button' component and I would like to include a href attribute so that when the button is clicked, it navigates to another page. An Issue Occurred: The following error was encountered: 'The type '{ ...

The marquee's position is reset the first time text is loaded dynamically from an API

In my angular project, I'm implementing a marquee feature to display data fetched from an API. However, I've noticed a strange issue where after a page reload, the marquee starts from right to left but once it reaches the end of the div, it reset ...

Try out NextJS API middleware by running tests with Jest

I have a middleware setup in my NextJS API route, located at /src/middleware/validateData/index.ts. It's used to validate request data using a schema. import { NextApiRequest, NextApiResponse } from 'next'; import schema from './schema ...

Webpack resolve.alias is not properly identified by Typescript

In the Webpack configuration, I have set up the following: usersAlias: path.resolve(__dirname, '../src/pages/users'), In my tsconfig.json, you can find: "baseUrl": ".", "paths": { "usersAlias/*": ["src/pages/users/*"], } This is how the cod ...

Tips for identifying the characteristics of a mobx observer in the developer console of a web browser

Within the project I am currently involved in, there is heavy reliance on dependency injection. In this context, you will come across code structures similar to the following: type BigWidget = { title: string, } const AProps = { b: BigWidget } cl ...

Next.js is having trouble identifying the module '@types/react'

Every time I attempt to launch my Next.js app using npm run dev, an error notification pops up indicating that the necessary packages for running Next with Typescript are missing: To resolve this issue, kindly install @types/react by executing: np ...

The scss function is returning an invalid property value

In my Angular project, I have organized my scss files/folders in the following way: 1) Settings - containing color settings and functions for the project 2) Files and folders defining variables such as fonts, widths, etc. for components and pages 3) Fil ...

Creative ways to design the HTML5 `<meter>` tag

I am curious about how to style the <meter> tag in a new way. <meter value=80 min=0 max=100> 80/100 </meter> All I want to do is customize the background color and the value color, but I haven't been able to locate the appropriat ...

Running TypeScript Jest tests in Eclipse 2020-12: A step-by-step guide

Having a TypeScript project with a test suite that runs smoothly using npm test in the project directory from the console. Is there a feature within Eclipse that can facilitate running these tests directly within the IDE, similar to how Java tests are ex ...

Implementing Avro file deserialization in a React application

I could really use some assistance with deserializing an avro file in a react application. I attempted to use the avsc npm package, but now I have encountered an error. const avro = require('avsc') ...... avro.createFileDecoder('./abc.avro&a ...

Inject the type into the dependency container

I am managing multiple databases without relying on ORM tools. Here, I will demonstrate an example using Postgres and MSSQL databases with UserQueries. https://i.sstatic.net/GFs5D.png Within my codebase, I have an interface called IDataBase which is impl ...