LoginSignup
2
1

More than 1 year has passed since last update.

ReactでLinkタグにstyled-componentでスタイルをあてたいとき

Last updated at Posted at 2021-05-11

React開発でstyled-componentを使用してスタイリングしていた際に、react-routerのLinkを使った時にどのようにCSSをあてるのか少し詰まったので自分用で記事にしておきます。

styled-componentの書き方

基本の書き方

<ThreadTitle>スレッド一覧</ThreadTitle>

export const ThreadTitle =styled.h2`
font-weight:bold;
font-size:20px;
`

ThreadTitleという定数を定義して、ラップしてあげる。
今回でいうとThreadTitleでラップされたスレッド一覧がh2タグで囲まれたことになり、スタイルがあたります。

aタグでも同様のことができると考え、下記のように記述しましたが、うまくいかず、、

<ThreadLink>リンク先</ThreadLink>

export const ThreadLink = styled.a`
    text-decoration: none;
    color: blue;
    font-size: 20px;
    margin: 5px 0;
    &:hover {
        opacity: 0.7;
        color: red;
    }
`;

結論、下記のように書き換えることで正しくCSSをあてることができました。

<ThreadLink>リンク先</ThreadLink>

export const ThreadLink = styled(Link)`
    text-decoration: none;
    color: blue;
    font-size: 20px;
    margin: 5px 0;
    &:hover {
        opacity: 0.7;
        color: red;
    }
`;

■参考
https://styled-components.com/docs/basics#styling-any-component

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