Home > database >  Change button background-color when button is clicked with lit components styleMap
Change button background-color when button is clicked with lit components styleMap

Time:11-04

I toggle between components on button click and I want to show active button when the user has clicked on a button. So backgroundColor of a clicked button should be green, but now when I click on one of the buttons, both buttons became green. How can I solve that so only one active button is green?

   @customElement('my-comp')
    export class myComp extends LitElement {
      static styles = css`
        .buttons-container {
          display: inline-flex;
          width: 100%;
          margin: 20px;
          gap: 20px;
        }
    
        button:active {
          background: green;
        }
    `
    
    @property() toggleComponent: boolean
    
      constructor() {
        super();
        this.toggleComponent = false;
      }
    
      private toggleComponentFunc() {
        this.toggleComponent = !this.toggleComponent
    
      }
    
      render() {
        
        const styles = {
          backgroundColor: this.toggleComponent ? 'lightgreen' : 'red',
    
        };
    
        const view = this.toggleComponent ?
        html`<comp-a></comp-a>` : html`<comp-b></comp-b>`
        return html`
            <div >
              <button  style=${styleMap(styles)} @click=${() => {this.toggleComponent = false;}}>
                comp A
              </button>
              <button  style=${styleMap(styles)} @click=${() => {this.toggleComponent = true;}}>
                comp B
              </button>
            </div>
    
            ${view}
        `;
    
      }
    }

This is the source question: What is the best way to toggle between two different Lit components?

CodePudding user response:

The issue is that both buttons are being passed the same styles.

const styles = {
  backgroundColor: this.toggleComponent ? 'lightgreen' : 'red',
};

If this.toggleComponent is true, styles will contain: background-color: 'lightgreen';, and then both buttons appear lightgreen.

A potential solution is to define the two style variants for the two buttons and pass them to the two buttons. Maybe something like:

// In render method (only showing changes)

    const stylesBtn1 = {
      backgroundColor: this.toggleComponent ? 'lightgreen' : 'red',
    };
    const stylesBtn2 = {
      backgroundColor: !this.toggleComponent ? 'lightgreen' : 'red',
    };

    return html`
      <button  style=${styleMap(stylesBtn1)}>
        comp A
      </button>
      <button  style=${styleMap(stylesBtn2)}>
        comp B
      </button>
    `;

Note that styleBtn1 uses this.toggleComponent and styleBtn2 uses !this.toggleComponent.

  • Related