LoginSignup
35
27

More than 5 years have passed since last update.

Reactでstyled-componentを使ってベースとなるstyleを当てる方法

Last updated at Posted at 2018-07-19

環境について

今回やりたいこと

Reactを使う場合は専らstyled-componentsを使っています。これを知ってからは手放せなくなってしまった。
やはり他のComponentにstyleが汚染されないのは良いですよね。

よくあるreset.cssとbaseとなるスタイルをstyled-componentsでReactのアプリに適用したいと思います。それによりwebpackなどでcss-loaderを使って別途cssを出力しなくてすみます!

基本的なやり方について

まずは基本的なとこから

App.jsやindex.jsなど全てのComponentをラップしているComponentのrenderの中でメソッドを呼び出すだけです。

class App extends React.Component{
  {/** 省略 **/}
  render() {
    baseStyles(theme)
    return (
      <ThemeProvider theme={theme}>
        {/** 省略 **/}
      </ThemeProvider>
    )
  }
}

injectGlobalについて

グローバルCSSを作成するヘルパーメソッドです。コンポーネントを返さず、スタイルシートにスタイルを直接追加することができます。

baseStyle

関数を作ってstyled-componentsのinjectGlobalというヘルパーメソッドを使うことで先ほどのようにbaseStyle()で呼び出すことができます。もちろん引数を渡すこともできるのでthemeを渡したりできますね。

import { injectGlobal } from 'styled-components'
import reset from 'styled-reset'
import { utilityStyles } from 'styles/utility'

const baseStyles = theme => injectGlobal`
  ${reset}
  // base.css
  html{
    font-size: ${theme.base.fontSize};
  }
  body {
    margin: 0;
    background: ${theme.color.white};
    color: ${theme.color.greyDarker};
    font-family: ${theme.base.fontFamily};
    font-size: 1em;
    line-height: ${theme.base.lineHeight};
    word-wrap: break-word;
    -webkit-text-size-adjust: 100%;
    -webkit-font-smoothing: antialiased;
  }
  a {
    cursor: pointer;

    &:link,
    &:visited {
      color: ${theme.color.greyDarker};
      text-decoration: none;
    }

    &:hover {
      opacity: .9;
      text-decoration: underline;
    }
  }
  h1,h2,h3,h4,h5, h6 {
    font-weight: 800;
  }
  #root {
    font-size: ${theme.font.size};
  }
  ${utilityStyles()}
`

export default baseStyles

styled-resetについて

zacanger/styled-reset: reset.css for styled-components

styled-components用のreset.cssです。使い方も簡単でこれでOK

import reset from 'styled-reset'
const baseStyles = () => injectGlobal`
  ${reset}
  /* other styles */
`

その他のCSSを使いたい

例えば以下のようのutility系のcssスタイルをとかをbaseStylesに加えたい場合は同じように関数を作って呼び出すだけです。

export const utilityStyles = () => css`
  .u-fz-10 {
    font-size: 1rem !important;
  }

  .u-fz-12 {
    font-size: 1.2rem !important;
  }

  .u-fz-14 {
    font-size: 1.4rem !important;
  }

  .u-fz-16 {
    font-size: 1.6rem !important;
  }

  .u-fz-18 {
    font-size: 1.8rem !important;
  }
`
const baseStyles = () => injectGlobal`
  ${utilityStyles()}
  /* other styles */
`
35
27
1

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
35
27