LoginSignup
3
2

More than 3 years have passed since last update.

TypeScriptでstyled-componentsを使う時propsでstyleの制御ができなくて困った時の解決法

Posted at

概要

TypeScriptでstyled-componentsを使いたくて公式ドキュメントのコードを写経していたら、
"Adapting based on props"の節の以下のコードが通らなくて困った。

const Button = styled.button`
  /* Adapt the colors based on primary prop */
  background: ${props => props.primary ? "palevioletred" : "white"};
  color: ${props => props.primary ? "white" : "palevioletred"};

  font-size: 1em;
  margin: 1em;
  padding: 0.25em 1em;
  border: 2px solid palevioletred;
  border-radius: 3px;
`;

原因

原因はpropsの部分に以下のエラーが出ていた。

> any
> プロパティ 'primary' は型 'ThemedStyledProps<Pick<DetailedHTMLProps<ButtonHTMLAttributes<HTMLButtonElement>, HTMLButtonElement>,
 "form" | ... 264 more ... | "value"> & { ...; }, any>' に存在しません。ts(2339)

解決法

interfaceを以下の様に定義してあげるとコンパイルが通った。

import styled, { StyledComponent } from 'styled-components';

interface ButtonProps {
  primary: boolean;
}

export const Button = styled.button<ButtonProps>`
  /* Adapt the colors based on primary prop */
  background: ${({primary}) => (primary ? 'palevioletred' : 'white')};
  color: ${({primary}) => (primary ? 'white' : 'palevioletred')};

  font-size: 1em;
  margin: 1em;
  padding: 0.25em 1em;
  border: 2px solid palevioletred;
  border-radius: 3px;
`;

ちなみにこのButtonコンポーネントを使う側のコードは以下の様になる。

import React from 'react';
import Button from '../../atoms/Button';

export const App: React.FC = () => {
  return (
    <>
      <Button primary={false}> Button </Button>
    </>
  );
};

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