LoginSignup
7

More than 5 years have passed since last update.

styled-componentsで使ってるあの文法はなに?

Last updated at Posted at 2018-06-08

styled-componentsとは

React向けにCSSをいい感じに書かせてくれるライブラリです。

const MyComponent = styled.div`
  font-size: 1.5em;
  text-align: center;
  color: palevioletred;
`;

render(<MyComponent />);

こんな感じで、記述できることはご存知かと思いますが、 styled.div`xxx`って何?と思いませんか?僕は思いました。

Tagged Template Literalというらしい

知りませんでした。

使い方

文法

こんな感じで、普通に関数を定義すればよいです。

function template() {
  // do something.
}

こんな感じで使います。

template`This is template`;

関数の呼び出され方

こうやって呼び出すと

template`This is ${foo} temp${bar}late`;

こんな感じで引数がわたってきます。

function template(arg1, arg2) {
  // arg1 = ["This is ", " temp", "late"];
  // arg2 = foo
  // arg3 = bar
}

第一引数は、${}で区切った文字列が配列で得られます。また、${}が文字列の最後に記述されていた場合は、配列の最後に空文字が入ります。${}が先頭にある場合も同様の挙動です。
${}の中身は、第二引数以降で得ることができます。

ユーザーが${}をいくつ使うかわかったものではありませんので、こんな感じで書くのが賢いのでしょう。
また、arg1とargsは交互に繋げると、もとの文字列が得られるようになっていますので、ご活用ください。

function template(arg1, ...args) {
  // arg1 = ["This is ", " temp", "late"];
  // args = [foo, bar]
}

使い道(追記)

ちょっと使い道を思いついたので、メモしておきます。
普通にconsole.log(`foo is ${foo}`);とやると、foo is [object Object]と出てしまうので、stringifyしてくれるとかっちょいいんじゃないでしょうか。
デバッグログで、適当にオブジェクトを挟めるのは助かりますね。

function log(texts, ...objects) {
  console.log(
    texts.map((text, i) => `${text}${JSON.stringify(objects[i]) || ""}`).join(""),
  );
}

const foo = {
  foo: "foo",
};
const bar = {
  bar: "bar",
}

log`foo is ${foo} bar is ${bar}`;
// foo is {"foo":"foo"} bar is {"bar":"bar"};

以上です。よろしくお願いいたします。

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