LoginSignup
10
13

More than 5 years have passed since last update.

React-FlexBox-Gridの使い方

Last updated at Posted at 2016-06-15

React-FlexBox-Gridflexgrid.css用のdivを生成するreact componentです。

CSS Modulesという実装方法を取っています。
webpackを使う場合、css-loaderを一緒に使う必要があります。

Component

次の三つのコンポーネントがあります

  • Grid
  • Row
  • Col

使い方はbootstrap3と大体同じです。実装にCSS flexible boxを使っています。

  1. Gridの中にRowを置きます。
  2. Rowの中にColを置きます。
  3. Colにxs={6}のように、幅を設定します。

index.jsx
const React = require('react')
const ReactDOM = require('react-dom')
const {Grid, Row, Col} = require('react-flexbox-grid');

const App = () =>
    <Grid>
      <Row>
        <Col xs={6} md={3}>Hello, world!</Col>
      </Row>
    </Grid>

ReactDOM.render(<App />, document.querySelector('#container'))
index.html
<!DOCTYPE html>
<html>
  <body>
    <div id="container"></div>
    <script src="bundle.js"></script>
  </body>
</html>

手順

準備

package.jsonを作ります。

npm init -y

必要なnpmモジュールをインストールします。

npm i -D webpack babel-loader babel-core babel-plugin-transform-react-jsx style-loader css-loader react react-dom react-flexbox-grid babel-polyfill classnames flexboxgrid

webpackの設定ファイルを作ります。

webpack.config.js
module.exports = {
  entry: './index.jsx',
  output: {
    filename: 'bundle.js'
  },
  module: {
    loaders: [{
      test: /\.jsx?$/,
      exclude: /node_modules/,
      loader: 'babel',
      query: {
        plugins: ["transform-react-jsx"]
      }
    }, {
      test: /\.css$/,
      loader: "style!css?modules"
    }]
  }
}

ビルド

node_modules/webpack/bin/webpack.js

実行

index.htmlを開くと次のようなDOMが生成されます。

<div id="container">
    <div data-reactroot="" class="R2zU9JsZW1r2id-qp7H3S">
        <div class="_1y_mg6OlZKhq9LGfUCMUme">
            <div class="_1DhV6KBVDhq0C7-sV3-jzc _3ANRSKqa19Npv87KFXEafn">Hello, world!</div>
        </div>
    </div>
</div>

classに謎の文字列が指定されています。

<style type="text/css">
    ._2lUES1qfK73keSn9S_BiQT,
    .R2zU9JsZW1r2id-qp7H3S {
        margin-right: auto;
        margin-left: auto;
    }

    ._2lUES1qfK73keSn9S_BiQT {
        padding-right: 2rem;
        padding-left: 2rem;
    }

headタグの中のstyleタグに謎の文字列クラスが定義されています。
CSS Modulesによって、コンポーネントに閉じたスタイルが作られているのがわかります。

注意書き

webpack.config.jsの定義で?modulesをつけるのがわからず、苦労しました。

className always empty · Issue #21 · roylee0704/react-flexbox-grid

Adding ?modules to the loader fixed it for me:
{
test: /.css/,
loader: "style!css?modules"
},

参考

10
13
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
10
13