LoginSignup
0
0

More than 1 year has passed since last update.

styled-componentsで独自コンポーネントにスタイルを当てるときはclassNameプロパティが必要です。

Last updated at Posted at 2022-07-11

はじめに

リファレンスの該当箇所に記載があります。

例えば

親コンポーネント(Index)で子コンポーネント(Typography)のスタイルを一部上書きしたい時

index.tsx
import React from "react";
import styled from 'styled-components';
import Typography from "./typography";

const ExtendTypo = styled(Typography)`
    font-size: 3rem
`

const Index: React.FC = () => {
    return (
        <>
            <Typography>ベースのfont-sizeは1rem</Typography>
            <ExtendTypo>これはfont-sizeが3remになるはず</ExtendTypo>
        </>
    );
};

export default Index;

うまくいかない例

typography.tsx
import React, { ReactNode } from 'react';
import styled from 'styled-components';

const StyledParagraph = styled.p`
    font-size: 1rem;
    margin: 0;
    line-height: 1.5;
`

type Props = {
    children: ReactNode
}

const Typography:React.FC<Props> = ({children}) => {
    return (
        <StyledParagraph>
            {children}
        </StyledParagraph>
    )
}

export default Typography;

スクリーンショット 2022-07-12 3.22.35.png

これでいける

子コンポーネントにclassNameプロパティを追加する

typography.tsx
import styled from 'styled-components';

const StyledParagraph = styled.p`
    font-size: 1rem;
    margin: 0;
    line-height: 1.5;
`

type Props = {
    children: ReactNode
    className?:string
}

const Typography:React.FC<Props> = ({children,className}) => {
    return (
        <StyledParagraph className={className}>
            {children}
        </StyledParagraph>
    )
}

export default Typography;

スクリーンショット 2022-07-12 3.23.37.png

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