Skip to content

Instantly share code, notes, and snippets.

@oudam-meas
Last active March 8, 2018 03:40
Show Gist options
  • Save oudam-meas/66de9fd1defafb49c49f778d6ecfa374 to your computer and use it in GitHub Desktop.
Save oudam-meas/66de9fd1defafb49c49f778d6ecfa374 to your computer and use it in GitHub Desktop.

Webpack + react

New rails projet

rails new react-rails-webpacker
cd react-rails-webpacker

Add Gems

open Gemfile and ADD below gem

gem 'webpacker', '~> 3.3'
gem 'react-rails', '~> 2.4', '>= 2.4.4'

Budling

In terminal

$ bundle

Installation

In terminal

$ bundle install
$ rails webpacker:install       # OR (on rails version < 5.0) rake webpacker:install
$ rails webpacker:install:react # OR (on rails version < 5.0) rake webpacker:install:react
$ rails generate react:install

Try importing application.js to application layout

Upon 'rails webpacker:install', a new file create app/javascripts/packs/application.js It can be include into the layouts(same purpose and similar usage of app/asset/javascripts/application.js)

<!-- application.html.erb -->
<%= javascript_pack_tag 'application' %>

Generating New component

In terminal ** with 'rails webpacker:install:react' specific file structure is generated for react file related(jsx). eg. app/javascripts/components. The below generating command will create a components file name HelloWorld.js under the component directory.**

$ rails g react:component HelloWorld greeting:string

Using new component

To use the component, we can put below method with component name, and passing param to our view file, such as index.html.erb

<!-- index.html.erb -->
<%= react_component("HelloWorld", { greeting: "Hello" }) %>

Working with stylesheet

Main style sheet file directory

create a file eg. applicatio.scss(css is also an option) under app/javascripts/src (we should create the 'src' directory).

Usage

include style sheet file into the app/javascripts/packs/application.js

/* app/javascripts/packs/application.js*/
import "../src/application.scss"

Call the stylesheet_pack_tag method in view layout, in this case 'application.html.erb'

<!-- views/layouts/application.html.erb -->
<%= stylesheet_pack_tag 'application' %>

re-run webpack with -w

In terminal

$ ./bin/webpack -w
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment