LoginSignup
0
0

More than 1 year has passed since last update.

css propを使うとき、自作コンポーネントのプロパティに'css'という名前は使えない

Posted at

結論

プロパティ名を'css'から'style'等の別名に変えればOK。
以上。

当方の環境は

  • @emotion/reactでスタイリングしている
  • typescriptのjsxImportSourceに@emotion/reactを入れることでcss propを実現
tsconfig.json
{
  "compilerOptions": {
    "jsxImportSource": "@emotion/react"
  }
}

現象:ReactのPropsでcss(スタイリング)情報を渡せない

以下のコードをデバッグ実行したところ、子コンポーネントのprops.cssがデフォルト値のままでした。

parentComponent.tsx
function ParentComponent(){
    return (
        <ChildComponent css={{backgroundColor:'black'}} />
    )
}
childComponent.tsx
import {css,Interpolation,Theme} from '@emotion/react';

interface Props{
    css?:Interpolation<Theme>;
}

export function ChildComponent(props:Props){
    const {css:style}=props;
    return (
        <div css={[{width:'10px',height:'10px'},style]} />
    )
}
ChildComponent.defaultProps={css:css({})}

困った。

解決:子コンポーネントのprop名を'css'以外にしたら通った

上記の通りです。

parentComponent.tsx
function ParentComponent(){
    return (
        <ChildComponent style={{backgroundColor:'black'}} />
    )
}
childComponent.tsx
import {css,Interpolation,Theme} from '@emotion/react';

interface Props{
    style?:Interpolation<Theme>;
}

export function ChildComponent(props:Props){
    const {style}=props;
    return (
        <div css={[{width:'10px',height:'10px'},style]} />
    )
}
ChildComponent.defaultProps={style:css({})}

原因(推測):'css'という名称のバッティング

  • @emotion/reactでデフォルトでcss propを持つ設定にしている
  • 子コンポーネント自身がcssというprop名を持っている

上記の場合、css propがで定義している方のプロパティが優先される仕様であると思われます。

手こずった要因

css propは、自身で定義したコンポーネントの場合、cssというpropを与えません。
実際、自作コンポーネントにcssというプロパティを与えようとするとコンパイルエラーとなります。
そのため自作コンポーネントでは'css'という名称はcss propには使用されていないという認識でした。

しかしどうやらcssという名前のプロパティは、トランスパイルする過程でcss propとして優先して処理されるようです。
トランスパイル前はcssというプロパティはたしかに存在しなかったため、名称のバッティングという可能性を考慮できませんでした。

理屈的にはESLintの設定を弄っていいかんじにする方法があるかも。

0
0
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
0
0