7
6

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Rails6にWebpackでMaterializeを導入

Posted at

Materialize導入

app/javascript/stylesheets/application.scssを追加
javascript配下にファイルがないのでまずファイルを作成する

コマンド実行
$ mkdir app/javascript/stylesheets
$ touch app/javascript/stylesheets/application.scss

作成したファイルに以下を追記

app/javascript/stylesheets/application.scss
@import 'materialize-css/dist/css/materialize';

app/javascript/packs/application.jsに以下を追加

app/javascript/packs/application.js
import '../stylesheets/application'
import 'materialize-css/dist/js/materialize'

app/views/layouts/application.html.erbに以下を追加

app/views/layouts/application.html.erb
<%= stylesheet_pack_tag 'application', media: 'all', 'data-turbolinks-track': 'reload' %>

materializeを追加

コマンド実行
yarn add materialize-css

最後に app/views/layouts/application.html.erb にiconを追加する

app/views/layouts/application.html.erb
<link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">

ちゃんと動くか確認してみる

app/views/layouts/application.html.erb にナビゲーションを追加する

app/views/layouts/application.html.erb
  <nav>
    <div class="nav-wrapper">
      <a href="#!" class="brand-logo center">Logo</a>
      <ul class="left hide-on-med-and-down">
        <li><a href="sass.html">Sass</a></li>
        <li><a href="badges.html">Components</a></li>
        <li class="active"><a href="collapsible.html">JavaScript</a></li>
      </ul>
    </div>
  </nav>

ヘッダーに以下が表示されていればOK

image.png

レスポンシブが効いていない

以下のようにレスポンシブが効いてない

app/views/layouts/application.html.erbheadに以下を追加する

app/views/layouts/application.html.erb
<meta name="viewport" content="width=device-width, initial-scale=1.0">

すると以下のように表示されるようになります

Selectが表示されない

Selectタグを使うと以下のようにうまく表示されない

image.png

app/views/layouts/application.html.erbに以下を追記

app/views/layouts/application.html.erb
  <script>
    document.addEventListener('DOMContentLoaded', function() {
      var elems = document.querySelectorAll('select');
      var instances = M.FormSelect.init(elems,[]);
    });
  </script>

すると以下のように表示されるようになる

materialize-select.gif

参照

How to install materialize-css on Rails 6.0.0.beta2 using Webpack

7
6
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
7
6

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?