Skip to content

Instantly share code, notes, and snippets.

@jonikorpi
Last active September 4, 2021 01:38
Show Gist options
  • Save jonikorpi/78070aab5e88d5e60e9c4c13ddde14c0 to your computer and use it in GitHub Desktop.
Save jonikorpi/78070aab5e88d5e60e9c4c13ddde14c0 to your computer and use it in GitHub Desktop.
Single-file components in React, using Constructable Stylesheets
// https://github.com/calebdwilliams/construct-style-sheets
import "construct-style-sheets-polyfill";
export default strings => {
if (document.readyState === "loading") {
window.addEventListener("DOMContentLoaded", () => adopt(strings));
} else {
adopt(strings);
}
};
const adopt = strings => {
const sheet = new CSSStyleSheet();
sheet.replace(strings.join(""));
document.adoptedStyleSheets = [...document.adoptedStyleSheets, sheet];
};
import React from "react";
import css from "./css.js";
export default ({ red, children }) => (
<div className={`example ${red ? "red" : ""}`}>
{children}
</div>
);
css`
.example {
color: blue;
}
.example.red {
color: red;
}
`;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment