LoginSignup
0
1

More than 3 years have passed since last update.

Styled-Componentを使いまわす

Last updated at Posted at 2021-03-25

Rails × react SPAの作成に当たりstyled-componentを使用している。
せっかくなのでstyled-componentを使いまわす練習がしたい(0からスタイル考えるのめんどくさいってのは内緒)

①コンポーネントをexport

styled-componentを定義している箇所でexportしましょう

export const FormBlock = styled.div `
  margin: 10px auto;
  width: 40%;
  display: flex;
  flex-direction: column;

②コンポーネントのimport

コンポーネントを使いまわす先でimportします。
このとき通常の名前付きexportの場合は{}で囲う必要があります。
default exportの場合は囲わなくていいみたいです。

//コンポーネントの読み込み
import {FormBlock} from "../common/UserModal.jsx"

今回は通常のexportなので{}で囲います。

③スタイルを継承しつつアレンジ

スタイルを継承しつつアレンジすることもできます。
その場合はexport先となるコンポーネントでスタイルを定義する際に
以下のように styled(継承したいコンポーネント名) と記述します。

const BooksFormBlock = styled(FormBlock)`
  width: 80%;
  & label {
    font-size: 16px;
  }
  & input {
    height: 24px;
    line-height: 24px;
  }

  & textarea {
    height: 100px;
    resize: none;
  }

`

こうするとexportしたコンポーネントのスタイルを踏まえつつ、アレンジしたいところだけ
アレンジできます。

実際にやってみました。

今回例としてモーダルウィンドウを使いまわしてみました。
かんたんにデザインに統一感が出せるので非常にありがたいですね。
recommended-books-3-2.gif

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