LoginSignup
5
2

More than 3 years have passed since last update.

【styled-components】styled(Component)でクラス名が付与されない

Posted at

あまりにも何回もやってしまうのでメモ。

styled-componentsではstyled.divとする以外に、既存のコンポーネントにstyled(Component)とする方法がある。

styled.div
import styled from "styled-components"

export const Component = styled.div`
  display: flex
  align-items: center
  justify-content: center
`
styled()
import styled from "styled-components"
import { BaseComponent } from "../components"

export const Component = styled(BaseComponent)`
  display: flex
  align-items: center
  justify-content: center
`

classNameを記述

React.FCコンポーネントをstyled(Component)でスタイリングする場合、classNameを受け取れるようにしておく必要がある。

OK
import React from 'react';

type Props = {
  className?: string;
};

const BaseComponent: React.FC<Props> = props => {
  return (
    <div className={props.className}>
      <div className="flex-center">{props.children}</div>
    </div>
  );
};

export const Component = styled(BaseComponent)`
  .flex-center {
    display: flex
    align-items: center
    justify-content: center
  }
`;
  • next.jsでの例。
    クラス名が注入されていることがわかる。
    スクリーンショット 2020-03-14 1.35.41.png
NG
import React from 'react';

const BaseComponent: React.FC= props => {
  return (
    <div>
      <div className="flex-center">{props.children}</div>
    </div>
  );
};

export const Component = styled(BaseComponent)`
  .flex-center {
    display: flex
    align-items: center
    justify-content: center
  }
`;

当たり前だが、コンポーネントがクラス名を受け取れないためクラス名が付与されない。
スクリーンショット 2020-03-14 1.36.28.png

5
2
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
5
2