Search code examples
bootstrap-4web-componentlit-element

How do you use Bootstrap with Lit-Element?


I would like to make use of Lit-Element with Bootstrap.

Currently I have simply imported the external dependancies as suggested here: https://lit-element.polymer-project.org/guide/styles#external-stylesheet

Is there a better way to import these 3rd party dependancies?

Here is my component:

import { LitElement, html, css } from "../../../third-party-libs/lit-element.js"

class LoginError extends LitElement {
  static get properties() { 
    return { 
      show: { type: Boolean, reflect: true }
    }
  }

  static get styles() {
    return css`
      div {
        color: red;
      }
      .hide-me {
        visibility: hidden
      }
    `;
  } 

  constructor() {
    super();
    this.show = false
  }

  render(){
    return html`
      <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.2.1/css/bootstrap.min.css" integrity="sha384-GJzZqFGwb1QTTN6wy59ffF1BuGJpLSa9DkKMp0DgiMDm4iYMj70gZWKYbI706tWS" crossorigin="anonymous">
      <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/animate.css/3.7.0/animate.min.css">
      <!-- jQuery first, then Popper.js, then Bootstrap JS -->
      <script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script>
      <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.6/umd/popper.min.js" integrity="sha384-wHAiFfRlMFy6i5SRaxvfOCifBUQy1xHdJ/yoi7FRNXMRBu5WHdZYu1hA6ZOblgut" crossorigin="anonymous"></script>
      <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.2.1/js/bootstrap.min.js" integrity="sha384-B0UglyR+jN6CkvvICOB2joaf5I4l3gm9GU6Hc1og6Ls7i6U/mkkaduKaBhlAXv9k" crossorigin="anonymous"></script>


      <div class="invalid-credentials mb-3 animated ${ this.show ? "shake" : "hide-me"}">
        Invalid credentials, please try again
      </div>
    `
  }
}

customElements.define('login-error', LoginError)

I would appreciate any advice on how to clean this up, and how to share this code with multiple components.


Solution

  • You can do this in get styles, this code extract the global style and attach it shadowdom, so the component ereditate the bootstrap and u ca overwrite if u want the style inside

      static get styles() {
        const { cssRules } = document.styleSheets[0]
        const globalStyle = css([Object.values(cssRules).map(rule => 
        rule.cssText).join('\n')])
        return [
          globalStyle,
          css`
          `
        ];
      }