StencilJS Component Styles - web-component

What is the proper way to use the styles option/property of the ComponentDecorator? Using the styles property with the default my-name component from the repository stencil-component-starter doesn't seem to affect the styles of the respective component nor generate something like a <style> tag in the <head>. How is styles intended to work? Or has it not been implemented yet? If the goal is to avoid having a separate CSS asset that needs to be loaded, but provide styles for the component, would styles be the right choice or is there another property such as host would need to be used?
Below is a sample component generated from the stencil-component-starter]1 with stylesUrl #Component property replaced with a styles property and setting font-size property. No errors are generated during dev or build tasks.
import { Component, Prop } from '#stencil/core';
#Component({
tag: 'my-name',
styles: `my-name { font-size: 24px; }`
})
export class MyName {
#Prop() first: string;
render() {
return (
<div>
Hello, my name is {this.first}
</div>
);
}
}
ComponentDecorator is defined as:
export interface ComponentOptions {
tag: string;
styleUrl?: string;
styleUrls?: string[] | ModeStyles;
styles?: string;
shadow?: boolean;
host?: HostMeta;
assetsDir?: string;
assetsDirs?: string[];
}
Thank you for any help you can provide!

I just tried with latest version 0.0.6-22, and it seems to work completely now.
While compiling, it will tell you if your styles contents is valid or not (mainly looking for valid selectors).
Here is a working example (with a simple string):
import { Component, Prop } from "#stencil/core";
#Component({
tag: "inline-css-example",
styles: 'inline-css-example { font-size: 24px; }'
})
export class InlineCSSExampleComponent {
#Prop() first: string;
render() {
return <div>Hello, my name is {this.first}</div>;
}
}
This one works too, with ES6 Template Strings (just showing multiline):
import { Component, Prop } from "#stencil/core";
#Component({
tag: "inline-templatestring-css-example",
styles: `
inline-templatestring-css-example {
font-size: 24px;
}
`
})
export class InlineCSSExampleComponent {
#Prop() first: string;
render() {
return <div>Hello, my name is {this.first}</div>;
}
}
(EDITed to show evolution since 0.0.6-13)

Related

Styles are not being picked up in my Lit component

I'm trying to implement a Lit component with some scss styling. Below is the component as it is right now:
import { html, LitElement } from 'lit-element';
import { ScopedElementsMixin } from '#open-wc/scoped-elements';
// Components
import 'inputmessage';
// Styles
import styles from './input-styles.scss';
export default class Input extends ScopedElementsMixin(LitElement) {
constructor() {
super();
}
static get properties() {
return {
label: { type: String, attribute: 'label' },
id: { type: String, attribute: 'id' },
value: { type: String, attribute: 'value' },
statusMessage: { type: String, attribute: 'status-message' },
statusType: { type: String, attribute: 'status-type' },
required: { type: Boolean, attribute: 'required' },
placeholder: { type: String, attribute: 'placeholder' },
type: { type: String, attribute: 'type' },
};
}
static get scopedElements() {
return {
'inputmessage': customElements.get('inputmessage'),
};
}
static get styles() {
return [styles];
}
render() {
return html`
<div>
${this.label && html`<label class="input-label" for="${this.id}">${this.label}</label>`}
<input type="${this.type}" required="${this.required}" value="${this.value}" placeholder="${this.placeholder}" id="${this.id}" name="${this.id}" />
</div>
`;
}
}
The CSS styles are in scss and only include the .input-label class. Now when I try to render the component on the screen it doesn't appear and I see the following message in the console output:
It seems the styles are not being picked up for some reason. I added the lit-scss-loader in my dependencies, but that also doesn't work. Anyone knows what I should do?
You need to use css tagged template function and unsafeCSS(str) function to make use of CSS imported into a string:
import { html, LitElement, css, unsafeCSS } from 'lit-element';
// later, inside your component class:
static get styles() {
return css`${unsafeCSS(styles)}`;
}
I have no clue what translates your SCSS, stopped using pre-processors years ago.
I can't comment so write new answer.
Lit don't process SCSS file.
If you need library check this library.
lit-scss-loader
other solution:
Convert scss to css manually then use this code.
import styles from './my-styles.css' assert { type: 'css' };
class MyEl extends LitElement {
static styles = [styles];
}
Note : above solution only work with chromium based browser.
Wait for other browser support.

Vaadin + LitElement - styles from `get styles()` not getting applied

I have a trivial LitElement class that I want to style with some internal CSS:
import {LitElement, html, css, customElement, property} from 'lit-element';
#customElement('address-card')
export class AddressCard extends LitElement {
#property()
streetAddress?: string;
#property()
postalCode?: string;
#property()
city?: string;
static get styles() {
return css`
.address { border: 1px dashed gray; }
`;
}
render() {
return html`
<div class="address">
<div>${this.streetAddress}</div>
<div>${this.postalCode} ${this.city}</div>
</div>
`;
// Remove this method to render the contents of this view inside Shadow DOM
createRenderRoot() {
return this;
}
}
The static get styles() method should allow me to add styles to the component, but nothing I add there seems to get applied. Not even a * { ... } selector, which should affect all elements, seems to do anything.
The problem is the createRenderRoot() method. If you disable shadow root, there's no need to encapsulate styles inside the component implementation - you can use global CSS. If you want to encapsulate styles, remove the createRenderRoot override and the static get styles() rules will get applied.

#aws-amplify/ui-react how to customize UI if my project uses SASS?

I'm extending a Next.js (React) project that was built by someone else, which uses .scss files (SASS) for styling. This is the project in question https://github.com/codebushi/nextjs-starter-dimension
Now I'm adding an authentication flow to the project using #aws-amplify/ui-react. Everything works fine, but I want to customize the UI style. I've found in the documentation that I can do that through :root in globals.css, as so:
:root {
--amplify-primary-color: #ff6347;
--amplify-primary-tint: #ff7359;
--amplify-primary-shade: #e0573e;
}
Documentation here: https://docs.amplify.aws/ui/customization/theming/q/framework/react
I know pretty much nothing about SASS except the basics. How would I do the equivalent of setting those variables in :root?
Edit with more details
This is my next.config.js:
module.exports = {
webpack: (config, { dev }) => {
config.module.rules.push(
{
test: /\.scss$/,
use: ['raw-loader', 'sass-loader']
}
)
return config
}
}
This is my authentication page where the Amplify elements are defined:
import { useState, useEffect } from 'react'
import { AuthState, onAuthUIStateChange } from '#aws-amplify/ui-components';
import { AmplifyAuthenticator, AmplifyAuthContainer, AmplifySignUp, AmplifySignIn, AmplifySignOut } from '#aws-amplify/ui-react';
import Router from 'next/router'
const Auth = (props) => {
const [authState, setAuthState] = useState();
const [user, setUser] = useState();
useEffect(() => {
return onAuthUIStateChange((nextAuthState, authData) => {
setAuthState(nextAuthState);
setUser(authData);
//console.log(`authData: ${JSON.stringify(authData, null, 2)}`);
});
}, []);
if (authState === AuthState.SignedIn && user) {
Router.push('https://mywebsite')
return <p>Redirecting...</p>
}
return (
<AmplifyAuthContainer>
<AmplifyAuthenticator usernameAlias="email">
<AmplifySignUp
slot="sign-up"
usernameAlias="email"
formFields={[
{
type: "email",
label: "Email Address *",
placeholder: "Enter your email address",
inputProps: { required: true },
},
{
type: "password",
label: "Password *",
placeholder: "Enter your password",
inputProps: { required: true },
},
]}
/>
<AmplifySignIn slot="sign-in" usernameAlias="email" />
</AmplifyAuthenticator>
</AmplifyAuthContainer>
);
}
export default Auth;
As per the answer below from Sean W, I've already tried creating an _app.js with:
import '../styles/global.scss'
const App = ({ Component, pageProps }) => {
return <Component {...pageProps} />
}
export default App;
with global.scss:
:root {
--amplify-primary-color: #ff6347;
--amplify-primary-tint: #ff7359;
--amplify-primary-shade: #e0573e;
}
But the CSS variables don't seem to be replaced.
Include the styles in your pages. The easiest way is to create a new SCSS file and include it in a custom _app.js.
By default, Next supports SASS - you only need to install the sass npm package and likely do not need a custom next.config. This could be one of your problems.
file - global.scss -
:root{
--amplify-primary-color: #ff6347;
--amplify-primary-shade: #e0573e;
}
//scoped & redeclared to an element with id #__next
:root #__next {
--amplify-primary-color: #ff6347;
--amplify-primary-shade: #e0573e;
}
Amplify could also be setting setting styles after you have already defined them for the :root - if this is the case you will need to scope your custom styles to take precedence over the default Amplify CSS variables. To do this - redeclare them in a CSS rule that is more specific than :root like the example above - keeping order of precedence in mind
Amplify also lets you directly target components.
amplify-authenticator {
--amplify-primary-color: #ff6347;
background: var(--amplify-primary-color);
padding: 5px;
}
// scoped & redeclared
:root #__next amplify-sign-in{
--amplify-primary-color: #ff6347;
}
The amplify elements that can be targeted are
amplify-authenticator
amplify-sign-in
amplify-confirm-sign-in
amplify-sign-up
amplify-confirm-sign-up
amplify-forgot-password
amplify-require-new-password
amplify-verify-contact
amplify-totp-setup
import your file - pages/_app.js
import 'path/to/global.scss';
const App = ({ Component, pageProps }) => <Component {...pageProps} />;
export default App;
Global variables (the equivalent of :root variables) can be created simply with this line.
$color = #c0ff33 !important;
The content can be anything that is available in css and partially sass.
For large projects, creating a variables.scss file and including in it all these variable declarations can be truly helpful for changing multiple variables at once. To include this file, just do #import "./variables.scss" at the top of your file.
Hope this helps! Good luck in your sassy endeavors!

Passing css styles from React Parent component to its child component

I have React parent component A which has its own scss file a-style.scss. Component B is child of A. A is passing styleInfo object as props which is applied on B.
My question is - is there any way we can define styleObj in a-style.scss instead of defining it inline. I want all styling related info should be in external scss file.
Component A
import "./a-style.scss";
import B from "./B.js";
class A extends Component {
constructor(props) {
super(props);
}
const styleObj = {
backgroundColor: "#F9F9F9",
borderRadius: '2px',
color: "#686868",
};
render() {
return (<B styleInfo={this.styleObj}></B>);
}
}
Component B
class B extends Component {
constructor(props) {
super(props);
}
render() {
return (<div style={this.props.styleInfo}></div>);
}
}
The standard way is to define CSS properties based on class in your scss/css. And then pass className from props in your React component:
class A extends Component {
theme = "themeA";
render() {
return (<B styleInfo={this.theme} />);
}
}
class B extends Component {
styleClass = ["B"];
render() {
const className = styleClass.push(this.props.styleInfo).join(' ');
return (<div className={className} />);
}
}
.themeA {
background-color: #F9F9F9;
border-radius: 2px;
color: #686868;
}
.B {
/* Some style for B component */
}
Why not just import that one file directly into B.js?
Is there any benefit of having it go through a parent, seems like necessary routing to me!
If you do need this, then I would just keep it in JS, as this is what JS is good at, or at least, have JS just do the className switching and, again, just have one css file that is a main style lookup hash!
Best of luck!

How to use custom component variable in custom component stylesheet?

Let's say I have a custom component - WoodComponent (/src/components/wood/wood.ts):
import { Component } from '#angular/core';
#Component({
selector: 'wood',
templateUrl: 'wood.html'
})
export class WoodComponent {
color: string = 'brown';
constructor() {}
}
How would I use the color variable in the component's stylesheet (/src/components/wood/wood.scss)? E.g.:
wood {
.wood-selected {
background-color: color($colors, [color variable from component]);
}
}
Thanks!
You need to declare brown inside variables.scss file and then use as shown below.
variables.scss
colors: ( primary: #488aff, brown: brown);
.scss
wood {
.wood-selected {
background-color: color($colors, brown);
}
}

Resources