react-rails 3.1.1 → 3.2.0

Sign up to get free protection for your applications and to get access to all the features.
checksums.yaml CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA256:
3
- metadata.gz: e21548e44de86710093640f1ec4b9fb7894a240d7f908cabcc9a6a0c271826dc
4
- data.tar.gz: 5879119b9a1c41c818896a82fc6b3596119e46b286eab96a54ad8489c803db5f
3
+ metadata.gz: f880539ce7f68ea781230ca57528e974c66e33f329e88e7033978c9d8243054d
4
+ data.tar.gz: c84e9c0426a5a7acc67b7c0d2a06a1f183042fee201aa417971ba40bcf857634
5
5
  SHA512:
6
- metadata.gz: dd4903039cd95c518f5b6cb9e5021711693cd0cca1a251d00957e5b03df88d87e5c2c57e1f1f6fbc24bf1d9553d8d23523c1f33caaa218e2953e5124e27874a5
7
- data.tar.gz: 830bf9d620edcc4084e88f330aa30a7f091cb56eed48d17bd7ca302878c912fa3ccead712bde0ba27369dad9d4e3768d5f28b564ac596672b8ec98bdbc2f2002
6
+ metadata.gz: 26113545fd0ead4c41ad391c8685e97205d9d8a7d15b8b6200a7e331ccf359a4aae1e765aa94666c39d6a2b5530bb6828fe0bf9031917a5ce46eb75a30a0dae8
7
+ data.tar.gz: 43f3f456fa55b25b13bc5fe5b3b535a1cff349b12f649ffcc1804ab49dbd13c0df8962c5fc1f9890ee4309137fa95f026ed0a58316ca71e670df9767551fed0f
data/CHANGELOG.md CHANGED
@@ -9,6 +9,15 @@ Changes since the last non-beta release.
9
9
 
10
10
  _Please add entries here for your pull requests that are not yet released._
11
11
 
12
+ #### Changed
13
+ - Make es6 and ts usable at same time. #1299
14
+ - Support other JS package managers using `package_json` gem #1306
15
+
16
+ ## [3.1.1] - 2023-08-16
17
+
18
+ #### Removed
19
+ - Removed the replace-null functionality due a severe logic error added in 3.1.0 #1300
20
+
12
21
  ## [3.1.0] - 2023-08-15
13
22
 
14
23
  #### Added
@@ -562,7 +571,8 @@ _Please add entries here for your pull requests that are not yet released._
562
571
  - Server rendering with `prerender: true`
563
572
  - Transform `.jsx` in the asset pipeline
564
573
 
565
- [Unreleased]: https://github.com/reactjs/react-rails/compare/v3.1.0...master
574
+ [Unreleased]: https://github.com/reactjs/react-rails/compare/v3.1.1...master
575
+ [3.1.1]: https://github.com/reactjs/react-rails/compare/v3.1.0...v3.1.1
566
576
  [3.1.0]: https://github.com/reactjs/react-rails/compare/v3.0.0...v3.1.0
567
577
  [3.0.0]: https://github.com/reactjs/react-rails/compare/v2.7.1...v3.0.0
568
578
  [2.7.1]: https://github.com/reactjs/react-rails/compare/v2.7.0...v2.7.1
data/README.md CHANGED
@@ -5,7 +5,7 @@
5
5
  [![Ruby](https://github.com/reactjs/react-rails/actions/workflows/ruby.yml/badge.svg)](https://github.com/reactjs/react-rails/actions/workflows/ruby.yml)
6
6
 
7
7
  ## News
8
- V3.0.0 is released with Shakapacker v6 support, including SSR. Please try it out and report any issues. We'll try to address any critical issues ASAP.
8
+ V3.0.0 is released with Shakapacker v7 support, including SSR. Please try it out and report any issues. We'll try to address any critical issues ASAP.
9
9
 
10
10
  For version 2.7 documentation checkout [2.7-stable](https://github.com/reactjs/react-rails/tree/2.7-stable) branch.
11
11
 
@@ -37,807 +37,50 @@ Read the [full review here](https://clutch.co/profile/shakacode#reviews?sort_by=
37
37
  * If you are upgrading, you might consider migrating to the [react_on_rails](https://github.com/shakacode/react_on_rails) gem.
38
38
  * Source code example utilizing React-Rails: https://github.com/BookOfGreg/react-rails-example-app
39
39
 
40
- <!-- START doctoc generated TOC please keep comment here to allow auto update -->
41
- <!-- DON'T EDIT THIS SECTION, INSTEAD RE-RUN doctoc TO UPDATE -->
42
- ## Contents
43
-
44
- - [Get started with Shakapacker](#get-started-with-shakapacker)
45
- - [Component name](#component-name)
46
- - [File naming](#file-naming)
47
- - [Typescript support](#typescript-support)
48
- - [Test component](#test-component)
49
- - [Use with Asset Pipeline](#use-with-asset-pipeline)
50
- - [Custom JSX Transformer](#custom-jsx-transformer)
51
- - [Transform Plugin Options](#transform-plugin-options)
52
- - [React.js versions](#reactjs-versions)
53
- - [View Helper](#view-helper)
54
- - [Custom View Helper](#custom-view-helper)
55
- - [UJS](#ujs)
56
- - [Mounting & Unmounting](#mounting--unmounting)
57
- - [Event Handling](#event-handling)
58
- - [`getConstructor`](#getconstructor)
59
- - [Server-Side Rendering](#server-side-rendering)
60
- - [Configuration](#configuration)
61
- - [JavaScript State](#javascript-state)
62
- - [Custom Server Renderer](#custom-server-renderer)
63
- - [Controller Actions](#controller-actions)
64
- - [Component Generator](#component-generator)
65
- - [Use with JBuilder](#use-with-jbuilder)
66
- - [Camelize Props](#camelize-props)
67
- - [Changing Component Templates](#changing-component-templates)
68
- - [Upgrading](#upgrading)
69
- - [2.7 to 3.0](#27-to-30)
70
- - [2.3 to 2.4](#23-to-24)
71
- - [Common Errors](#common-errors)
72
- - [Getting warning for `Can't resolve 'react-dom/client'` in React < 18](#getting-warning-for-cant-resolve-react-domclient-in-react--18)
73
- - [Undefined Set](#undefined-set)
74
- - [Using TheRubyRacer](#using-therubyracer)
75
- - [HMR](#hmr)
76
- - [Related Projects](#related-projects)
77
- - [Contributing](#contributing)
78
-
79
- <!-- END doctoc generated TOC please keep comment here to allow auto update -->
80
-
40
+ ## Documentation
41
+
42
+ - [Get started](docs/get-started.md)
43
+ - [Use with Shakapacker](docs/get-started.md#use-with-shakapacker)
44
+ - [Component name](docs/get-started.md#component-name)
45
+ - [File naming](docs/get-started.md#file-naming)
46
+ - [Typescript support](docs/get-started.md#typescript-support)
47
+ - [Test component](docs/get-started.md#test-component)
48
+ - [Use with Asset Pipeline](docs/get-started.md#use-with-asset-pipeline)
49
+ - [Custom JSX Transformer](docs/get-started.md#custom-jsx-transformer)
50
+ - [Transform Plugin Options](docs/get-started.md#transform-plugin-options)
51
+ - [React.js versions](docs/get-started.md#reactjs-versions)
52
+ - [View Helper](docs/view-helper.md)
53
+ - [Custom View Helper](docs/view-helper.md#custom-view-helper)
54
+ - [UJS](docs/ujs.md)
55
+ - [Mounting & Unmounting](docs/ujs.md#mounting--unmounting)
56
+ - [Event Handling](docs/ujs.md#event-handling)
57
+ - [`getConstructor`](docs/ujs.md#getconstructor)
58
+ - [Server-Side Rendering](docs/server-side-rendering.md)
59
+ - [Configuration](docs/server-side-rendering.md#configuration)
60
+ - [JavaScript State](docs/server-side-rendering.md#javascript-state)
61
+ - [Custom Server Renderer](docs/server-side-rendering.md#custom-server-renderer)
62
+ - [Controller Actions](docs/controller-actions.md)
63
+ - [Component Generator](docs/component-generator.md)
64
+ - [Use with JBuilder](docs/component-generator.md#use-with-jbuilder)
65
+ - [Camelize Props](docs/component-generator.md#camelize-props)
66
+ - [Changing Component Templates](docs/component-generator.md#changing-component-templates)
67
+ - [Upgrading](docs/upgrading.md)
68
+ - [2.7 to 3.0](docs/upgrading.md#27-to-30)
69
+ - [2.3 to 2.4](docs/upgrading.md#23-to-24)
70
+ - [Migrating from `react-rails` to `react_on_rails`](docs/migrating-from-react-rails-to-react_on_rails.md)
71
+ - [Why migrate?](docs/migrating-from-react-rails-to-react_on_rails.md#why-migrate)
72
+ - [Steps to migrate](docs/migrating-from-react-rails-to-react_on_rails.md#steps-to-migrate)
73
+ - [Common Errors](docs/common-errors.md)
74
+ - [Getting warning for `Can't resolve 'react-dom/client'` in React < 18](docs/common-errors.md#getting-warning-for-cant-resolve-react-domclient-in-react--18)
75
+ - [Undefined Set](docs/common-errors.md#undefined-set)
76
+ - [Using TheRubyRacer](docs/common-errors.md#using-therubyracer)
77
+ - [HMR](docs/common-errors.md#hmr)
78
+ - [Tests in component directory](docs/common-errors.md#tests-in-component-directory)
81
79
 
82
80
  After reading this README file, additional information about React-Rails can be found in the Wiki page:
83
81
  https://github.com/reactjs/React-Rails/wiki
84
82
  The Wiki page features a significant amount of additional information about React-Rails which includes instructional articles and answers to the most frequently asked questions.
85
83
 
86
-
87
- ## Get started with Shakapacker
88
-
89
- _Alternatively, get started with [Sprockets](#use-with-asset-pipeline)_
90
-
91
- 1. Create a new Rails app:
92
- Prevent installing default javascript dependencies by using `--skip-javascript` option:
93
-
94
- ```bash
95
- rails new my-app --skip-javascript
96
- cd my-app
97
- ```
98
-
99
- 2. Install `shakapacker`:
100
- ```bash
101
- bundle add shakapacker --strict
102
- rails shakapacker:install
103
- ```
104
-
105
- 3. Install `react` and some other required npm packages:
106
- ```bash
107
- yarn add react react-dom @babel/preset-react prop-types \
108
- css-loader style-loader mini-css-extract-plugin css-minimizer-webpack-plugin
109
- ```
110
-
111
- Also update the Babel configuration in the `package.json` file:
112
-
113
- ```diff
114
- "babel": {
115
- "presets": [
116
- - "./node_modules/shakapacker/package/babel/preset.js"
117
- + "./node_modules/shakapacker/package/babel/preset.js",
118
- + "@babel/preset-react"
119
- ]
120
- },
121
- ```
122
-
123
- 4. Install `react-rails`:
124
- ```bash
125
- $ bundle add 'react-rails' --strict
126
- $ rails generate react:install
127
- ```
128
-
129
- This gives you:
130
-
131
- - `app/javascript/components/` directory for your React components
132
- - [`ReactRailsUJS`](#ujs) setup in `app/javascript/packs/application.js`
133
- - `app/javascript/packs/server_rendering.js` for [server-side rendering](#server-side-rendering)
134
-
135
- 5. Generate your first component:
136
- ```bash
137
- $ rails g react:component HelloWorld greeting:string
138
- ```
139
-
140
- You can also generate your component in a subdirectory:
141
-
142
- ```bash
143
- $ rails g react:component my_subdirectory/HelloWorld greeting:string
144
- ```
145
-
146
- Note: Your component is added to `app/javascript/components/` by default.
147
-
148
- Note: If your component is in a subdirectory you will append the directory path to your erb component call.
149
-
150
- Example:
151
- ```erb
152
- <%= react_component("my_subdirectory/HelloWorld", { greeting: "Hello from react-rails." }) %>
153
- ```
154
-
155
- 6. [Render it in a Rails view](#view-helper):
156
-
157
- ```erb
158
- <!-- erb: paste this in view -->
159
- <%= react_component("HelloWorld", { greeting: "Hello from react-rails." }) %>
160
- ```
161
-
162
- 7. Lets Start the app:
163
- ```bash
164
- $ rails s
165
- ```
166
- Output: greeting: Hello from react-rails", inspect webpage in your browser to see the change in tag props.
167
-
168
- 8. Run dev server (optional)
169
- In order to run dev server with HMR feature you need to parallely run:
170
-
171
- ```bash
172
- $ ./bin/shakapacker-dev-server
173
- ```
174
-
175
- Note: On Rails 6 you need to specify `webpack-dev-server` host. To this end, update `config/initializers/content_security_policy.rb` and uncomment relevant lines.
176
-
177
- ### Component name
178
-
179
- The component name tells `react-rails` where to load the component. For example:
180
-
181
- `react_component` call | component `require`
182
- -----|-----
183
- `react_component("Item")` | `require("Item")`
184
- `react_component("items/index")` | `require("items/index")`
185
- `react_component("items.Index")` | `require("items").Index`
186
- `react_component("items.Index.Header")` | `require("items").Index.Header`
187
-
188
- This way, you can access top-level, default, or named exports.
189
-
190
- The `require.context` inserted into `packs/application.js` is used to load components. If you want to load components from a different directory, override it by calling `ReactRailsUJS.useContext`:
191
-
192
- ```js
193
- var myCustomContext = require.context("custom_components", true)
194
- var ReactRailsUJS = require("react_ujs")
195
- // use `custom_components/` for <%= react_component(...) %> calls
196
- ReactRailsUJS.useContext(myCustomContext)
197
- ```
198
-
199
- If `require` fails to find your component, [`ReactRailsUJS`](#ujs) falls back to the global namespace, described in [Use with Asset Pipeline](#use-with-asset-pipeline).
200
-
201
- In some cases, having multiple `require.context` entries may be desired. Examples of this include:
202
-
203
- - Refactoring a typical Rails application into a Rails API with an (eventually) separate Single Page Application (SPA). For this use case, one can add a separate pack in addition to the typical `application` one. React components can be shared between the packs but the new pack can use a minimal Rails view layout, different default styling, etc.
204
- - In a larger application, you might find it helpful to split your JavaScript by routes/controllers to avoid serving unused components and improve your site performance by keeping bundles smaller. For example, you might have separate bundles for homepage, search, and checkout routes. In that scenario, you can add an array of `require.context` component directory paths via `useContexts` to `server_rendering.js`, to allow for [Server-Side Rendering](#server-side-rendering) across your application:
205
-
206
- ```js
207
- // server_rendering.js
208
- var homepageRequireContext = require.context('homepage', true);
209
- var searchRequireContext = require.context('search', true);
210
- var checkoutRequireContext = require.context('checkout', true);
211
-
212
- var ReactRailsUJS = require('react_ujs');
213
- ReactRailsUJS.useContexts([
214
- homepageRequireContext,
215
- searchRequireContext,
216
- checkoutRequireContext
217
- ]);
218
- ```
219
- ### File naming
220
-
221
- React-Rails supports plenty of file extensions such as: .js, .jsx.js, .js.jsx, .es6.js, .coffee, etcetera!
222
- Sometimes this will cause a stumble when searching for filenames.
223
-
224
- Component File Name | `react_component` call
225
- -----|-----
226
- `app/javascript/components/samplecomponent.js` | `react_component("samplecomponent")`
227
- `app/javascript/components/sample_component.js` | `react_component("sample_component")`
228
- `app/javascript/components/SampleComponent.js` | `react_component("SampleComponent")`
229
- `app/javascript/components/SampleComponent.js.jsx` | Has to be renamed to SampleComponent.jsx, then use `react_component("SampleComponent")`
230
-
231
- ### Typescript support
232
-
233
- ```bash
234
- yarn add typescript @babel/preset-typescript
235
- ```
236
-
237
- Babel won’t perform any type-checking on TypeScript code. To optionally use type-checking run:
238
-
239
- ```bash
240
- yarn add fork-ts-checker-webpack-plugin
241
- ```
242
-
243
- Add `tsconfig.json` with the following content:
244
-
245
- ```json
246
- {
247
- "compilerOptions": {
248
- "declaration": false,
249
- "emitDecoratorMetadata": true,
250
- "experimentalDecorators": true,
251
- "lib": ["es6", "dom"],
252
- "module": "es6",
253
- "moduleResolution": "node",
254
- "sourceMap": true,
255
- "target": "es5",
256
- "jsx": "react",
257
- "noEmit": true
258
- },
259
- "exclude": ["**/*.spec.ts", "node_modules", "vendor", "public"],
260
- "compileOnSave": false
261
- }
262
- ```
263
-
264
- Then modify the webpack config to use it as a plugin:
265
-
266
- ```js
267
- // config/webpack/webpack.config.js
268
- const { webpackConfig, merge } = require("shakapacker");
269
- const ForkTSCheckerWebpackPlugin = require("fork-ts-checker-webpack-plugin");
270
-
271
- module.exports = merge(webpackConfig, {
272
- plugins: [new ForkTSCheckerWebpackPlugin()],
273
- });
274
- ```
275
-
276
- Doing this will allow React-Rails to support the .tsx extension. Additionally, it is recommended to add `ts` and `tsx` to the `server_renderer_extensions` in your application configuration:
277
-
278
- ```ruby
279
- config.react.server_renderer_extensions = ["jsx", "js", "tsx", "ts"]
280
- ```
281
-
282
- ### Test component
283
-
284
- You can use `assert_react_component` to test component render:
285
-
286
- ```erb
287
- <!-- app/views/welcome/index.html.erb -->
288
-
289
- <%= react_component("HelloWorld", { greeting: "Hello from react-rails.", info: { name: "react-rails" } }, { class: "hello-world" }) %>
290
- ```
291
-
292
- ```rb
293
- class WelcomeControllerTest < ActionDispatch::IntegrationTest
294
- test 'assert_react_component' do
295
- get "/welcome"
296
- assert_equal 200, response.status
297
-
298
- # assert rendered react component and check the props
299
- assert_react_component "HelloWorld" do |props|
300
- assert_equal "Hello from react-rails.", props[:greeting]
301
- assert_equal "react-rails", props[:info][:name]
302
- assert_select "[class=?]", "hello-world"
303
- end
304
-
305
- # or just assert component rendered
306
- assert_react_component "HelloWorld"
307
- end
308
- end
309
- ```
310
-
311
- ## Use with Asset Pipeline
312
-
313
- `react-rails` provides a pre-bundled React.js & a UJS driver to the Rails asset pipeline. Get started by adding the `react-rails` gem:
314
-
315
- ```ruby
316
- gem 'react-rails'
317
- ```
318
-
319
- And then install the react generator:
320
-
321
- ```
322
- $ rails g react:install
323
- ```
324
-
325
- Then restart your development server.
326
-
327
- This will:
328
-
329
- - add some `//= require`s to `application.js`
330
- - add a `components/` directory for React components
331
- - add `server_rendering.js` for [server-side rendering](#server-side-rendering)
332
-
333
- Now, you can create React components in `.jsx` files:
334
-
335
- ```JSX
336
- // app/assets/javascripts/components/post.jsx
337
-
338
- window.Post = createReactClass({
339
- render: function() {
340
- return <h1>{this.props.title}</h1>
341
- }
342
- })
343
-
344
- // or, equivalent:
345
- class Post extends React.Component {
346
- render() {
347
- return <h1>{this.props.title}</h1>
348
- }
349
- }
350
- ```
351
-
352
- Then, you can render those [components in views](#view-helper):
353
-
354
- ```erb
355
- <%= react_component("Post", {title: "Hello World"}) %>
356
- ```
357
-
358
- Components must be accessible from the top level, but they may be namespaced, for example:
359
-
360
- ```erb
361
- <%= react_component("Comments.NewForm", {post_id: @post.id}) %>
362
- <!-- looks for `window.Comments.NewForm` -->
363
- ```
364
-
365
- ### Custom JSX Transformer
366
-
367
- `react-rails` uses a transformer class to transform JSX in the asset pipeline. The transformer is initialized once, at boot. You can provide a custom transformer to `config.react.jsx_transformer_class`. The transformer must implement:
368
-
369
- - `#initialize(options)`, where options is the value passed to `config.react.jsx_transform_options`
370
- - `#transform(code_string)` to return a string of transformed code
371
-
372
- `react-rails` provides two transformers, `React::JSX::BabelTransformer` (which uses [ruby-babel-transpiler](https://github.com/babel/ruby-babel-transpiler)) and `React::JSX::JSXTransformer` (which uses the deprecated `JSXTransformer.js`).
373
-
374
- #### Transform Plugin Options
375
-
376
- To supply additional transform plugins to your JSX Transformer, assign them to `config.react.jsx_transform_options`
377
-
378
- `react-rails` uses the Babel version of the `babel-source` gem.
379
-
380
- For example, to use `babel-plugin-transform-class-properties` :
381
-
382
- config.react.jsx_transform_options = {
383
- optional: ['es7.classProperties']
384
- }
385
-
386
- ### React.js versions
387
-
388
- `//= require react` brings `React` into your project.
389
-
390
- By default, React's [development version] is provided to `Rails.env.development`. You can override the React build with a config:
391
-
392
- ```ruby
393
- # Here are the defaults:
394
- # config/environments/development.rb
395
- MyApp::Application.configure do
396
- config.react.variant = :development
397
- end
398
-
399
- # config/environments/production.rb
400
- MyApp::Application.configure do
401
- config.react.variant = :production
402
- end
403
- ```
404
-
405
- Be sure to restart your Rails server after changing these files. See [VERSIONS.md](https://github.com/reactjs/react-rails/blob/master/VERSIONS.md) to learn which version of React.js is included with your `react-rails` version. In some edge cases you may need to bust the sprockets cache with `rake tmp:clear`
406
-
407
-
408
- ## View Helper
409
-
410
- `react-rails` includes a view helper and an [unobtrusive JavaScript driver](#ujs) which work together to put React components on the page.
411
-
412
- The view helper (`react_component`) puts a `div` on the page with the requested component class & props. For example:
413
-
414
- ```erb
415
- <%= react_component('HelloMessage', name: 'John') %>
416
- <!-- becomes: -->
417
- <div data-react-class="HelloMessage" data-react-props="{&quot;name&quot;:&quot;John&quot;}"></div>
418
- ```
419
-
420
- On page load, the [`react_ujs` driver](#ujs) will scan the page and mount components using `data-react-class`
421
- and `data-react-props`.
422
-
423
- The view helper's signature is:
424
-
425
- ```ruby
426
- react_component(component_class_name, props={}, html_options={})
427
- ```
428
-
429
- - `component_class_name` is a string which identifies a component. See [getConstructor](#getconstructor) for details.
430
- - `props` is either:
431
- - an object that responds to `#to_json`; or
432
- - an already-stringified JSON object (see [JBuilder note](#use-with-jbuilder) below).
433
- - `html_options` may include:
434
- - `tag:` to use an element other than a `div` to embed `data-react-class` and `data-react-props`.
435
- - `prerender: true` to render the component on the server.
436
- - `camelize_props` to [transform a props hash](#camelize-props)
437
- - `**other` Any other arguments (eg `class:`, `id:`) are passed through to [`content_tag`](http://api.rubyonrails.org/classes/ActionView/Helpers/TagHelper.html#method-i-content_tag).
438
-
439
-
440
- #### Custom View Helper
441
-
442
- `react-rails` uses a "helper implementation" class to generate the output of the `react_component` helper. The helper is initialized once per request and used for each `react_component` call during that request. You can provide a custom helper class to `config.react.view_helper_implementation`. The class must implement:
443
-
444
- - `#react_component(name, props = {}, options = {}, &block)` to return a string to inject into the Rails view
445
- - `#setup(controller_instance)`, called when the helper is initialized at the start of the request
446
- - `#teardown(controller_instance)`, called at the end of the request
447
-
448
- `react-rails` provides one implementation, `React::Rails::ComponentMount`.
449
-
450
- ## UJS
451
-
452
- `react-rails`'s JavaScript is available as `"react_ujs"` in the asset pipeline or from NPM. It attaches itself to the window as `ReactRailsUJS`.
453
-
454
- ### Mounting & Unmounting
455
-
456
- Usually, `react-rails` mounts & unmounts components automatically as described in [Event Handling](#event-handling) below.
457
-
458
- You can also mount & unmount components from `<%= react_component(...) %>` tags using UJS:
459
-
460
- ```js
461
- // Mount all components on the page:
462
- ReactRailsUJS.mountComponents()
463
- // Mount components within a selector:
464
- ReactRailsUJS.mountComponents(".my-class")
465
- // Mount components within a specific node:
466
- ReactRailsUJS.mountComponents(specificDOMnode)
467
-
468
- // Unmounting works the same way:
469
- ReactRailsUJS.unmountComponents()
470
- ReactRailsUJS.unmountComponents(".my-class")
471
- ReactRailsUJS.unmountComponents(specificDOMnode)
472
- ```
473
-
474
- You can use this when the DOM is modified by AJAX calls or modal windows.
475
-
476
- ### Event Handling
477
-
478
- `ReactRailsUJS` checks for various libraries to support their page change events:
479
-
480
- - `Turbolinks`
481
- - `pjax`
482
- - `jQuery`
483
- - Native DOM events
484
-
485
- `ReactRailsUJS` will automatically mount components on `<%= react_component(...) %>` tags and unmount them when appropriate.
486
-
487
- If you need to re-detect events, you can call `detectEvents`:
488
-
489
- ```js
490
- // Remove previous event handlers and add new ones:
491
- ReactRailsUJS.detectEvents()
492
- ```
493
-
494
- For example, if `Turbolinks` is loaded _after_ `ReactRailsUJS`, you'll need to call this again. This function removes previous handlers before adding new ones, so it's safe to call as often as needed.
495
-
496
- If `Turbolinks` is `import`ed via Shakapacker (and thus not available globally), `ReactRailsUJS` will be unable to locate it. To fix this, you can temporarily add it to the global namespace:
497
-
498
- ```js
499
- // Order is particular. First start Turbolinks:
500
- Turbolinks.start();
501
- // Add Turbolinks to the global namespace:
502
- window.Turbolinks = Turbolinks;
503
- // Remove previous event handlers and add new ones:
504
- ReactRailsUJS.detectEvents();
505
- // (Optional) Clean up global namespace:
506
- delete window.Turbolinks;
507
- ```
508
-
509
- ### `getConstructor`
510
-
511
- Components are loaded with `ReactRailsUJS.getConstructor(className)`. This function has two default implementations, depending on if you're using the asset pipeline or Shakapacker:
512
-
513
- - On the asset pipeline, it looks up `className` in the global namespace (`ReactUJS.constructorFromGlobal`).
514
- - On Shakapacker, it `require`s files and accesses named exports, as described in [Get started with Shakapacker](#get-started-with-shakapacker), falling back to the global namespace (`ReactUJS.constructorFromRequireContextWithGlobalFallback`).
515
-
516
- You can override this function to customize the mapping of name-to-constructor. [Server-side rendering](#server-side-rendering) also uses this function.
517
-
518
- For example, the fallback behavior of
519
- `ReactUJS.constructorFromRequireContextWithGlobalFallback` can sometimes make
520
- server-side rendering errors hard to debug as it will swallow the original error
521
- (more info
522
- [here](https://github.com/reactjs/react-rails/issues/264#issuecomment-552326663)).
523
- `ReactUJS.constructorFromRequireContext` is provided for this reason. You can
524
- use it like so:
525
-
526
- ```js
527
- // Replaces calls to `ReactUJS.useContext`
528
- ReactUJS.getConstructor = ReactUJS.constructorFromRequireContext(require.context('components', true));
529
- ```
530
-
531
-
532
- ## Server-Side Rendering
533
-
534
- You can render React components inside your Rails server with `prerender: true`:
535
-
536
- ```erb
537
- <%= react_component('HelloMessage', {name: 'John'}, {prerender: true}) %>
538
- <!-- becomes: -->
539
- <div data-react-class="HelloMessage" data-react-props="{&quot;name&quot;:&quot;John&quot;}">
540
- <h1>Hello, John!</h1>
541
- </div>
542
- ```
543
-
544
- _(It will also be mounted by the [UJS](#ujs) on page load.)_
545
-
546
- Server rendering is powered by [`ExecJS`](https://github.com/rails/execjs) and subject to some requirements:
547
-
548
- - `react-rails` must load your code. By convention, it uses `server_rendering.js`, which was created
549
- by the install task. This file must include your components _and_ their dependencies (eg, Underscore.js).
550
- - Requires separate compilations for server & client bundles (see [Webpack config](https://github.com/reactjs/react-rails/tree/master/test/dummy/config/webpack))
551
- - Your code can't reference `document` or `window`. Prerender processes don't have access to `document` or `window`,
552
- so jQuery and some other libs won't work in this environment :(
553
-
554
- `ExecJS` supports many backends. CRuby users will get the best performance from [`mini_racer`](https://github.com/discourse/mini_racer#performance).
555
-
556
- #### Configuration
557
-
558
- Server renderers are stored in a pool and reused between requests. Threaded Rubies (eg jRuby) may see a benefit to increasing the pool size beyond the default `0`.
559
-
560
- These are the default configurations:
561
-
562
- ```ruby
563
- # config/application.rb
564
- # These are the defaults if you don't specify any yourself
565
- module MyApp
566
- class Application < Rails::Application
567
- # Settings for the pool of renderers:
568
- config.react.server_renderer_pool_size ||= 1 # ExecJS doesn't allow more than one on MRI
569
- config.react.server_renderer_timeout ||= 20 # seconds
570
- config.react.server_renderer = React::ServerRendering::BundleRenderer
571
- config.react.server_renderer_options = {
572
- files: ["server_rendering.js"], # files to load for prerendering
573
- replay_console: true, # if true, console.* will be replayed client-side
574
- }
575
- # Changing files matching these dirs/exts will cause the server renderer to reload:
576
- config.react.server_renderer_extensions = ["jsx", "js"]
577
- config.react.server_renderer_directories = ["/app/assets/javascripts", "/app/javascript/"]
578
- end
579
- end
580
- ```
581
-
582
- #### JavaScript State
583
-
584
- Some of ExecJS's backends are stateful (eg, mini_racer, therubyracer). This means that any side-effects of a prerender will affect later renders with that renderer.
585
-
586
- To manage state, you have a couple options:
587
-
588
- - Make a custom renderer with `#before_render` / `#after_render` hooks as [described below](#custom-server-renderer)
589
- - Use `per_request_react_rails_prerenderer` to manage state for a whole controller action.
590
-
591
- To check out a renderer for the duration of a controller action, call the `per_request_react_rails_prerenderer` helper in the controller class:
592
-
593
- ```ruby
594
- class PagesController < ApplicationController
595
- # Use the same React server renderer for the entire request:
596
- per_request_react_rails_prerenderer
597
- end
598
- ```
599
-
600
- Then, you can access the ExecJS context directly with `react_rails_prerenderer.context`:
601
-
602
- ```ruby
603
- def show
604
- react_rails_prerenderer # => #<React::ServerRendering::BundleRenderer>
605
- react_rails_prerenderer.context # => #<ExecJS::Context>
606
-
607
- # Execute arbitrary JavaScript code
608
- # `self` is the global context
609
- react_rails_prerenderer.context.exec("self.Store.setup()")
610
- render :show
611
- react_rails_prerenderer.context.exec("self.Store.teardown()")
612
- end
613
- ```
614
-
615
- `react_rails_prerenderer` may also be accessed in before- or after-actions.
616
-
617
- #### Custom Server Renderer
618
-
619
- `react-rails` depends on a renderer class for rendering components on the server. You can provide a custom renderer class to `config.react.server_renderer`. The class must implement:
620
-
621
- - `#initialize(options={})`, which accepts the hash from `config.react.server_renderer_options`
622
- - `#render(component_name, props, prerender_options)` to return a string of HTML
623
-
624
- `react-rails` provides two renderer classes: `React::ServerRendering::ExecJSRenderer` and `React::ServerRendering::BundleRenderer`.
625
-
626
- `ExecJSRenderer` offers two other points for extension:
627
-
628
- - `#before_render(component_name, props, prerender_options)` to return a string of JavaScript to execute _before_ calling `React.render`
629
- - `#after_render(component_name, props, prerender_options)` to return a string of JavaScript to execute _after_ calling `React.render`
630
-
631
- Any subclass of `ExecJSRenderer` may use those hooks (for example, `BundleRenderer` uses them to handle `console.*` on the server).
632
-
633
- ## Controller Actions
634
-
635
- Components can also be server-rendered directly from a controller action with the custom `component` renderer. For example:
636
-
637
- ```ruby
638
- class TodoController < ApplicationController
639
- def index
640
- @todos = Todo.all
641
- render component: 'TodoList', props: { todos: @todos }, tag: 'span', class: 'todo'
642
- end
643
- end
644
- ```
645
-
646
- You can also provide the "usual" `render` arguments: `content_type`, `layout`, `location` and `status`. By default, your current layout will be used and the component, rather than a view, will be rendered in place of `yield`. Custom data-* attributes can be passed like `data: {remote: true}`.
647
-
648
- Prerendering is set to `true` by default, but can be turned off with `prerender: false`.
649
-
650
- ## Component Generator
651
-
652
- You can generate a new component file with:
653
-
654
- ```sh
655
- rails g react:component ComponentName prop1:type prop2:type ... [options]
656
- ```
657
-
658
- For example,
659
-
660
- ```sh
661
- rails g react:component Post title:string published:bool published_by:instanceOf{Person}
662
- ```
663
-
664
- would generate:
665
-
666
- ```JSX
667
- var Post = createReactClass({
668
- propTypes: {
669
- title: PropTypes.string,
670
- published: PropTypes.bool,
671
- publishedBy: PropTypes.instanceOf(Person)
672
- },
673
-
674
- render: function() {
675
- return (
676
- <React.Fragment>
677
- Title: {this.props.title}
678
- Published: {this.props.published}
679
- Published By: {this.props.publishedBy}
680
- </React.Fragment>
681
- );
682
- }
683
- });
684
- ```
685
-
686
- The generator also accepts options:
687
-
688
- - `--es6`: generates a function component
689
- - `--coffee`: use CoffeeScript
690
-
691
- For example,
692
-
693
- ```sh
694
- rails g react:component ButtonComponent title:string --es6
695
- ```
696
-
697
- would generate:
698
-
699
- ```jsx
700
- import React from "react"
701
- import PropTypes from "prop-types"
702
-
703
- function ButtonComponent(props) {
704
- return (
705
- <React.Fragment>
706
- Title: {this.props.title}
707
- </React.Fragment>
708
- );
709
- }
710
-
711
- ButtonComponent.propTypes = {
712
- title: PropTypes.string
713
- };
714
-
715
- export default ButtonComponent
716
- ```
717
-
718
- **Note:** In a Shakapacker project, es6 template is the default template in the generator.
719
-
720
- Accepted PropTypes are:
721
-
722
- - Plain types: `any`, `array`, `bool`, `element`, `func`, `number`, `object`, `node`, `shape`, `string`
723
- - `instanceOf` takes an optional class name in the form of `instanceOf{className}`.
724
- - `oneOf` behaves like an enum, and takes an optional list of strings in the form of `'name:oneOf{one,two,three}'`.
725
- - `oneOfType` takes an optional list of react and custom types in the form of `'model:oneOfType{string,number,OtherType}'`.
726
-
727
- Note that the arguments for `oneOf` and `oneOfType` must be enclosed in single quotes
728
- to prevent your terminal from expanding them into an argument list.
729
-
730
- #### Use with JBuilder
731
-
732
- If you use Jbuilder to pass a JSON string to `react_component`, make sure your JSON is a stringified hash,
733
- not an array. This is not the Rails default -- you should add the root node yourself. For example:
734
-
735
- ```ruby
736
- # BAD: returns a stringified array
737
- json.array!(@messages) do |message|
738
- json.extract! message, :id, :name
739
- json.url message_url(message, format: :json)
740
- end
741
-
742
- # GOOD: returns a stringified hash
743
- json.messages(@messages) do |message|
744
- json.extract! message, :id, :name
745
- json.url message_url(message, format: :json)
746
- end
747
- ```
748
-
749
- ### Camelize Props
750
-
751
- You can configure `camelize_props` option:
752
-
753
- ```ruby
754
- MyApp::Application.configure do
755
- config.react.camelize_props = true # default false
756
- end
757
- ```
758
-
759
- Now, Ruby hashes given to `react_component(...)` as props will have their keys transformed from _underscore_- to _camel_-case, for example:
760
-
761
- ```ruby
762
- { all_todos: @todos, current_status: @status }
763
- # becomes:
764
- { "allTodos" => @todos, "currentStatus" => @status }
765
- ```
766
-
767
- You can also specify this option in `react_component`:
768
-
769
- ```erb
770
- <%= react_component('HelloMessage', {name: 'John'}, {camelize_props: true}) %>
771
- ```
772
-
773
- ### Changing Component Templates
774
-
775
- To make simple changes to Component templates, copy the respective template file to your Rails project at `lib/templates/react/component/template_filename`.
776
-
777
- For example, to change the [ES6 Component template](https://github.com/reactjs/react-rails/blob/master/lib/generators/templates/component.es6.jsx), copy it to `lib/templates/react/component/component.es6.jsx` and modify it.
778
-
779
- ## Upgrading
780
-
781
- ### 2.7 to 3.0
782
- - Keep your `react_ujs` up to date: `yarn upgrade`
783
- - **Drop support for Webpacker:** Before any ReactRails upgrade, make sure upgrading from Webpacker to Shakapacker 7. For more information check out Shakapacker
784
- - **SSR:** ReactRails 3.x requires separate compilations for server & client bundles. See [Webpack config](https://github.com/reactjs/react-rails/tree/master/test/dummy/config/webpack) directory in the dummy app to addapt the new implementation.
785
-
786
- ### 2.3 to 2.4
787
-
788
- Keep your `react_ujs` up to date, `yarn upgrade`
789
-
790
- React-Rails 2.4.x uses React 16+ which no longer has React Addons. Therefore the pre-bundled version of react no longer has an addons version, if you need addons still, there is the 2.3.1+ version of the gem that still has addons.
791
-
792
- If you need to make changes in your components for the prebundled react, see the migration docs here:
793
-
794
- - https://reactjs.org/blog/2016/11/16/react-v15.4.0.html
795
- - https://reactjs.org/blog/2017/04/07/react-v15.5.0.html
796
- - https://reactjs.org/blog/2017/06/13/react-v15.6.0.html
797
-
798
-
799
- For the vast majority of cases this will get you most of the migration:
800
- - global find+replace `React.Prop` -> `Prop`
801
- - add `import PropTypes from 'prop-types'` (Webpacker only)
802
- - re-run `bundle exec rails webpacker:install:react` to update npm packages (Webpacker only)
803
-
804
- ## Common Errors
805
- ### Getting warning for `Can't resolve 'react-dom/client'` in React < 18
806
-
807
- You may see a warning like this when building a Webpack bundle using any version of React below 18. This warning can be safely [suppressed](https://webpack.js.org/configuration/other-options/#ignorewarnings) in your Webpack configuration. The following is an example of this suppression in `config/webpack/webpack.config.js`:
808
-
809
- ```diff
810
- - const { webpackConfig } = require('shakapacker')
811
- + const { webpackConfig, merge } = require('shakapacker')
812
-
813
- +const ignoreWarningsConfig = {
814
- + ignoreWarnings: [/Module not found: Error: Can't resolve 'react-dom\/client'/],
815
- +};
816
-
817
- - module.exports = webpackConfig
818
- + module.exports = merge({}, webpackConfig, ignoreWarningsConfig)
819
- ```
820
-
821
- ### Undefined Set
822
- ```
823
- ExecJS::ProgramError (identifier 'Set' undefined):
824
-
825
- (execjs):1
826
- ```
827
- If you see any variation of this issue, see [Using TheRubyRacer](#using-therubyracer)
828
-
829
-
830
- ### Using TheRubyRacer
831
- TheRubyRacer [hasn't updated LibV8](https://github.com/cowboyd/therubyracer/blob/master/therubyracer.gemspec#L20) (The library that powers Node.js) from v3 in 2 years, any new features are unlikely to work.
832
-
833
- LibV8 itself is already [beyond version 7](https://github.com/cowboyd/libv8/releases/tag/v7.3.492.27.1) therefore many serverside issues are caused by old JS engines and fixed by using an up to date one such as [MiniRacer](https://github.com/discourse/mini_racer) or [TheRubyRhino](https://github.com/cowboyd/therubyrhino) on JRuby.
834
-
835
- ### HMR
836
-
837
- Check out [Enabling Hot Module Replacement (HMR)](https://github.com/shakacode/shakapacker/blob/master/docs/react.md#enabling-hot-module-replacement-hmr) in Shakapacker documentation.
838
-
839
- One caveat is that currently you [cannot Server-Side Render along with HMR](https://github.com/reactjs/react-rails/issues/925#issuecomment-415469572).
840
-
841
84
  ## Related Projects
842
85
 
843
86
  - [webpacker-react](https://github.com/renchap/webpacker-react): Integration of React with Rails utilizing Webpack with Hot Module Replacement (HMR).
@@ -256,14 +256,20 @@ module React
256
256
  def detect_template_extension
257
257
  if options[:coffee]
258
258
  "js.jsx.coffee"
259
+ elsif options[:ts] && es6_enabled?
260
+ "es6.tsx"
259
261
  elsif options[:ts]
260
262
  "js.jsx.tsx"
261
- elsif options[:es6] || shakapacker?
263
+ elsif es6_enabled?
262
264
  "es6.jsx"
263
265
  else
264
266
  "js.jsx"
265
267
  end
266
268
  end
269
+
270
+ def es6_enabled?
271
+ options[:es6] || shakapacker?
272
+ end
267
273
  end
268
274
  end
269
275
  end
@@ -103,8 +103,19 @@ module React
103
103
  ReactRailsUJS.useContext(componentRequireContext);
104
104
  JS
105
105
 
106
+ def require_package_json_gem
107
+ require "bundler/inline"
108
+
109
+ gemfile(true) { gem "package_json" }
110
+
111
+ puts "using package_json v#{PackageJson::VERSION}"
112
+ end
113
+
106
114
  def setup_react_shakapacker
107
- `yarn add react_ujs`
115
+ require_package_json_gem
116
+
117
+ PackageJson.read.manager.add(["react_ujs"])
118
+
108
119
  if manifest.exist?
109
120
  append_file(manifest, SHAKAPACKER_SETUP_UJS)
110
121
  else
@@ -0,0 +1,24 @@
1
+ <%= file_header %>
2
+ interface I<%= component_name %>Props {
3
+ <% if attributes.size > 0 -%>
4
+ <% attributes.each do |attribute| -%>
5
+ <% if attribute[:union] -%>
6
+ <%= attribute[:name].camelize(:lower) %>: <%= attribute[:name].titleize %>;
7
+ <% else -%>
8
+ <%= attribute[:name].camelize(:lower) %>: <%= attribute[:type] %>;
9
+ <% end -%>
10
+ <% end -%>
11
+ <% end -%>
12
+ }
13
+
14
+ const <%= component_name %> = (props: I<%= component_name %>Props) => {
15
+ return (
16
+ <React.Fragment>
17
+ <% attributes.each do |attribute| -%>
18
+ <%= attribute[:name].titleize %>: {props.<%= attribute[:name].camelize(:lower) %>}
19
+ <% end -%>
20
+ </React.Fragment>
21
+ )
22
+ }
23
+
24
+ <%= file_footer %>
@@ -4,6 +4,6 @@ module React
4
4
  module Rails
5
5
  # If you change this, make sure to update VERSIONS.md
6
6
  # and republish the UJS by updating package.json and `bundle exec rake ujs:publish`
7
- VERSION = "3.1.1"
7
+ VERSION = "3.2.0"
8
8
  end
9
9
  end
metadata CHANGED
@@ -1,7 +1,7 @@
1
1
  --- !ruby/object:Gem::Specification
2
2
  name: react-rails
3
3
  version: !ruby/object:Gem::Version
4
- version: 3.1.1
4
+ version: 3.2.0
5
5
  platform: ruby
6
6
  authors:
7
7
  - Paul O’Shannessy
@@ -11,7 +11,7 @@ authors:
11
11
  autorequire:
12
12
  bindir: bin
13
13
  cert_chain: []
14
- date: 2023-08-16 00:00:00.000000000 Z
14
+ date: 2024-01-10 00:00:00.000000000 Z
15
15
  dependencies:
16
16
  - !ruby/object:Gem::Dependency
17
17
  name: appraisal
@@ -209,6 +209,20 @@ dependencies:
209
209
  - - ">="
210
210
  - !ruby/object:Gem::Version
211
211
  version: '0'
212
+ - !ruby/object:Gem::Dependency
213
+ name: package_json
214
+ requirement: !ruby/object:Gem::Requirement
215
+ requirements:
216
+ - - ">="
217
+ - !ruby/object:Gem::Version
218
+ version: '0'
219
+ type: :development
220
+ prerelease: false
221
+ version_requirements: !ruby/object:Gem::Requirement
222
+ requirements:
223
+ - - ">="
224
+ - !ruby/object:Gem::Version
225
+ version: '0'
212
226
  - !ruby/object:Gem::Dependency
213
227
  name: connection_pool
214
228
  requirement: !ruby/object:Gem::Requirement
@@ -302,6 +316,7 @@ files:
302
316
  - lib/generators/react/component_generator.rb
303
317
  - lib/generators/react/install_generator.rb
304
318
  - lib/generators/templates/component.es6.jsx
319
+ - lib/generators/templates/component.es6.tsx
305
320
  - lib/generators/templates/component.js.jsx
306
321
  - lib/generators/templates/component.js.jsx.coffee
307
322
  - lib/generators/templates/component.js.jsx.tsx