7
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

hyperappで使えるcss in js、「picostyle」

Last updated at Posted at 2018-02-28

最近ReactのスタイリングをするときにStyled-componentを使うのにはまってるんですが、hyperappでも同じようにできたらいいなぁと思って探してみたらあったので紹介です。

Picostyle

Picostyle is a 0.4 KB CSS-in-JS library for use with frameworks that expose an h function.

Picostyleは0.4kbのCSS-in-JSのライブラリで、h関数を公開しているフレームワークと共に使うそうで、現在動作確認ができているのが、hyperapppicodomの2つです。

インストール

npmやyarn、cndからのインストールが可能です。

npm i --save picostyle
yarn add picostyle
<script src="https://unpkg.com/picostyle"></script>

scriptタグで読み込んだ場合、window.picostyleでアクセスできるようになるそうです。

使い方

picostyleはh関数を公開しているフレームワークと共に使われます。そして、picostyle関数にh関数をわたすと、そのh関数と同様の振る舞いをする高階関数を返します。

import { h } from "some-framework"
import picostyle from "picostyle"

const style = picostyle(h)

この高階関数はタグ名または、スタイルの適用されていないコンポーネントを受け取り、スタイル(JSON)を受け取る関数を返します。

// Styled component from tag name
const Wrapper = style("div")({
  minHeight: "100vh",
  background: "#000",
})

// Styling an un-styled component
const Component = text => h("h1", {}, text)
const Text = style(Component)({
  color: "#fff",
})

もし、propsの値からスタイルを定義したい場合は、JSONのかわりに関数を渡すことができます。

// Here we set the color of the button, based on the color prop
const Button = style("button")(props => ({
  color: props.color
}))

picostyleは受けとったJSON(または関数)を単純なCSSに変更し、ドキュメントの先頭のスタイルタグに埋め込みます。picostyleによるスタイル付けされたコンポーネントはユニークな識別子をクラス名として持っています。

そして、出力はInlineStyleではなくStyleSheetであるため、MediaQuery、擬似クラス、ネストした子要素などの複雑なスタイルを書けるみたいです。

サンプル

http://sosukesuzuki.me/ 僕のgh-pagesですが、これはhyperappとpicostyleで作りました。
リポジトリは、https://github.com/sosukesuzuki/sosukesuzuki.github.io/ です。
(追記:2018.4.6、僕のgh-pagesは更新されHyperappを使ったものではなくなりました。)

感想

便利だけど、それこそStyled-componentsのようにCSSみたいに書けたらいいですね。

7
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
7
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?