CSS-in-JS with Emotion
Last updated
Was this helpful?
Was this helpful?
// src/resources/attributes/emotion.ts
import { resolve } from 'aurelia';
import { css, cache } from '@emotion/css';
export class EmotionCustomAttribute {
private element: Element = resolve(Element);
attached() {
if (this.isInShadow(this.element)) {
cache.sheet.container = (this.element.getRootNode() as ShadowRoot).querySelector('style') || this.element.getRootNode();
} else {
cache.sheet.container = document.head;
}
this.element.classList.add(css(this.value));
}
private isInShadow(element: Element): boolean {
return element.getRootNode() instanceof ShadowRoot;
}
}// src/main.ts
import Aurelia from 'aurelia';
import { EmotionCustomAttribute } from './resources/attributes/emotion';
import { MyApp } from './my-app';
Aurelia
.register(EmotionCustomAttribute)
.app(MyApp)
.start();// src/my-app.ts
export class MyApp {
public message = 'Hello World!';
public cssObject = {
backgroundColor: 'hotpink',
'&:hover': {
color: 'white'
}
};
}<!-- src/my-app.html -->
<template>
<div emotion.bind="cssObject">${message}</div>
</template>