自作ブログを作っています。
技術スタック
- TypeScript
- React
- Next.js
- Styled Components
- GitHub Pages
今回は、Styled Componentsを導入します。
Styled Components
Scoped CSS の代表例の1つとして、Styled Componentsを導入してみます。
複数の選択肢がある中で、正直言ってまだどれが良さそうかまだ分かっておらず、試しでの導入となります。
前回仮に導入したCSS Modulesとの大きな違いとして、CSSファイルに記述するCSS Modulesと異なり、Styled ComponentsではJSでCSSの内容を変更することができます。
Styled Componentsの導入
npmを介して導入します。型定義ファイル(@types/XX
)も同時に導入します。
npm i styled-components; npm i -D @types/styled-components
次にCSSを記述していきます。
import styled from 'styled-components' const Article = styled.article` h1 { font-size: 2em; } h2 { font-size: 1.5em; } h3 { font-size: 1.2em; } ` const ArticleContent = ({ content, title, date }: Props) => { return ( <Article> <small>{date.format('YYYY-MM-DD')}</small> <h1>{title}</h1> <div dangerouslySetInnerHTML={{ __html: content }} /> </Article> ) }
ここでは記事ページのheader elementの文字サイズを指定しています。
標準の<article>
について、直接利用する代わりにstyled.article
の箇所でstyle適用を行った<Article>
を利用できるようになります。
import styled from 'styled-components' const MOBILE_MAX_WIDTH = '768px' const TABLET_MAX_WIDTH = '1024px' const ArticleContainer = styled.div` width: ${TABLET_MAX_WIDTH}; margin: 0 auto; padding: 0 15px; @media (max-width: ${TABLET_MAX_WIDTH}) { width: ${MOBILE_MAX_WIDTH}; } @media (max-width: ${MOBILE_MAX_WIDTH}) { width: 100%; } ` const Slug = ({ content, title, date }: Props) => { return ( <ArticleContainer> <ArticleContent content={content} date={dayjs(date)} title={title} /> </ArticleContainer> ) }
同様に、<dev>
にstyle適用を行った<ArticleContainer>
を作成・利用しています。
warning Prop did not match.の修正
画面で動作を見てみると、Warning: Prop
classNamedid not match. Server: "sc-dkrFOg fHFomc" Client: "sc-bcXHqe dqbIaK"
というWarningが出ています。
これについては、下記の記事を参考にさせていただいて修正しました。
Next.jsでstyled-componentsを使うときに最初に設定しておくこと【完全版】
babel-plugin-styled-components を導入・適用します。
npm i -D babel-plugin-styled-components
(.babelrc) { "presets": ["next/babel"], "plugins": ["babel-plugin-styled-components"] }
無事Warningを解消することができました。
Pull Request
https://github.com/nek0meshi/blog/pull/9
あとがき
最近観たTempalayのライブ、最高でした。
ROTTENGRAFFTYのライブでメガネが曲がりました。