LoginSignup
3
4

More than 5 years have passed since last update.

Styled Components の component selector パターンで React Components を指定する

Last updated at Posted at 2018-07-31

Styled Components の component selector パターンで若干ハマったので備忘録として書き留める。

Styled Components は component selector パターン を使用することで他のコンポーネントを参照することが可能である。

const A = styled.div``;

const B = styled.div`
  ${A} {
  }
`;

しかし、component selector パターンで React Components を指定するとエラーが発生する。

class A extends React.Component {
  render() {
    return <div />;
  }
}

const B = styled.div`
  ${A} {
  }
`;

TypeError: Cannot call a class as a function

勿論、 Functional Components もエラーが発生する。

const A = () => <div />;

const B = styled.div`
  ${A} {
  }
`;

TypeError: Cannot convert a Symbol value to a string

このエラーの原因としては、 component selector パターンは、 Styled Components のコンテキスト内でのみサポートされているためである。
上記の A コンポーネントは React.Component のインスタンスであり、Styled Component ではない。

styled() ファクトリー関数で React Component をラップすることで解決することができる。

class A extends React.Component {
  render() {
    return <div />;
  }
}

const StyledA = styled(A)``;

const B = styled.div`
  ${StyledA} {
  }
`;

React Components を import した後、 styled() ファクトリー関数で毎度ラップするのが面倒な場合は、 export 時にラップしてあげれば良い。

export default styled(A)``;

詳細については以下の記事を参照してください。

全ての React コンポーネントを Styled Component として export すべきでは?というお話 - Qiita

3
4
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
3
4