[TSX] inline-styleでCSS変数を指定する


Next.jsで開発を行っているとき、TSXからCSS変数を指定して、SASS Moduleでその値を使いたい時がある。

<ul style={{'--length': array.lenght}}>
   <li>{array}</li>
</ul>

ただ、CSSPropertiesにリストアップされている名前ではないため、TSXはエラーを吐く。

Types of property 'style' are incompatible.
Type '{ '--length': number; }' is not assignable to type 'CSSProperties'.
  Object literal may only specify known properties, and ''--length'' does not exist in type 'CSSProperties'.

なので、as React.CSSPropertiesを追加してあげることで動くようになる。

<ul style={{'--length': array.lenght}  as React.CSSProperties}>
   <li>{array}</li>
</ul>

別枠で書いてあげることもできるけど、こっちの方がスマートで書きやすい。

ただこの時点でTSXの想定上、あまりスマートではないことを実現しようとしているんだと思う。(JSXで動くコードであれば、拡張子をJSXに変えるだけでエラーは出ずに動く。本末転倒。)

reactjs – How to define css variables in style attribute in React and typescript – Stack Overflow https://stackoverflow.com/questions/52005083/how-to-define-css-variables-in-style-attribute-in-react-and-typescript

Add support for CSS variables in style attributes · Issue #6411 · facebook/react https://github.com/facebook/react/issues/6411


コメントを残す

メールアドレスが公開されることはありません。 が付いている欄は必須項目です