I tried to create a custom element navbar using shadowDom with its styling, namely bootsrap. I installed the bootstrap using NPM. then I imported the bootstrap in my style.scss and took the navbar element from bootstrap to apply to my custom element, but in the application process my navbar did not have any styling which might be caused by the bootstrap styling failing to penetrate the shadowDom earlier, has anyone experienced this ??? Here's my code and file structure I also use webpack to bundle it Structure Folder
my style.scss
@import 'bootstrap/scss/bootstrap';
$bg : rgb(192, 253, 255);
body {
background-color: $bg;
}
navbar.js
class NavBar extends HTMLElement {
constructor() {
super();
this.shadowDOM = this.attachShadow({
mode: 'open'
});
}
connectedCallback() {
this.render();
}
render() {
this.shadowRoot.innerHTML = `
<nav class="navbar navbar-expand-lg bg-body-tertiary">
<div class="container-fluid">
<a class="navbar-brand" href="#">Navbar</a>
<button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarNav" aria-controls="navbarNav" aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse" id="navbarNav">
<ul class="navbar-nav">
<li class="nav-item">
<a class="nav-link active" aria-current="page" href="#">Home</a>
</li>
<li class="nav-item">
<a class="nav-link" href="#">Features</a>
</li>
<li class="nav-item">
<a class="nav-link" href="#">Pricing</a>
</li>
<li class="nav-item">
<a class="nav-link disabled" aria-disabled="true">Disabled</a>
</li>
</ul>
</div>
</div>
</nav>
`;
}
}
customElements.define("nav-bar", NavBar);
index.js
import * as bootstrap from 'bootstrap';
import css from './style/style.scss';
import './script/component/nav-bar.js';
import main from './script/view/main.js';
document.addEventListener('DOMContentLoaded', main);
I want to use this bootsrap to make the custom element styling process easier.
The bootstrap style is added to the page, which doesn't penetrate shadow DOMs boundaries (which is part of the whole web-components encapsulation concept). To work aroud this, you need to add the style to your custom elements shadow root. there is couple of options. in general using a
<style>element with the css in it added to your shadowRoots innerHTML is the easiest, but i assume you will have more than only one custom element and bootstraps css not being small, that isn't a best performance wise approach. A better and more modern approach is to useadoptedStyleSheets(that has support in all major browsers now). i.e.if you are using webpack's css-loader, there is an option to outomatically get it as CSSStyleSheet. see: https://webpack.js.org/loaders/css-loader/#exporttype
css-style-sheet:Of course you also need to load you own css also into your shadow DOM. Where you do the same and add it via