Skip to content

Instantly share code, notes, and snippets.

@loktevich
Last active May 7, 2020 20:55
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save loktevich/292e27404786136c9f80302041b5a207 to your computer and use it in GitHub Desktop.
Save loktevich/292e27404786136c9f80302041b5a207 to your computer and use it in GitHub Desktop.
LWC. Interesting approach to style standard LWC components
/* Dark lightning datatable without header actions simplified example */
/* Better to create selectors with your entire component (c-my-component) */
c-my-component lightning-datatable .slds-th__action-button {
display: none;
}
/* Sometimes it needs to create more specific selectors as standard components may contain another componenets */
c-my-component lightning-datatable th .slds-cell-fixed {
background-color: #333;
color: #fff;
}
c-my-component lightning-datatable th .slds-cell-fixed:hover {
color: #111;
}
c-my-component lightning-datatable .slds-table tr {
background-color: #555;
color: #fff;
}
c-my-component lightning-datatable .slds-table tr:hover {
color: #111;
}
import { LightningElement, api, track } from "lwc";
import myComponent from "./myComponent.css";
export default class SearchResults extends LightningElement {
// Adds a style element (only once)
renderedCallBack() {
if (!this.hasRendered) {
const style = document.createElement("style");
// imported myComponent contains an object with a function(t,e,s)
// which can return a css content
style.innerText = searchResults["0"](null, "");
this.template
.querySelector("lightning-datatable")
.appendChild(style);
this.hasRendered = true;
}
}
}
@loktevich
Copy link
Author

Appending style element it's not ideal and you can break shadow DOM encapsulation. To keep advantages of shadow DOM it is better to create selectors starting from the component itself:

c-my-component lightning-datatable .slds-table {
    /* rules... */
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment