react-rails 3.1.0 → 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: 1f3c2b4f28629f4fa197ec51a3951aa90ca430a4688f0f45d8eceac3a91c7309
4
- data.tar.gz: 43f8580d6678c51cc0f6a7037dda28f63e256073ed7c5d16867c87d31d15af35
3
+ metadata.gz: f880539ce7f68ea781230ca57528e974c66e33f329e88e7033978c9d8243054d
4
+ data.tar.gz: c84e9c0426a5a7acc67b7c0d2a06a1f183042fee201aa417971ba40bcf857634
5
5
  SHA512:
6
- metadata.gz: b2a3fdff4d9d1438d9935b1d63b9fa1e891d6a79cce5dfd10731c364681b4d1cfc0c017960184c15d91c1228b5efb18fbe5e600f509ad0385f9d3c667894ac15
7
- data.tar.gz: 84500c2291940cfeb41617f340ce59ee7e9de4f2a337b5b313dc42581fa5157b7ecaac759d00d5240b80cb48154e57eb590bce5183e951b01691deb3d9bd9898
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,829 +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
- - [Other features](#other-features)
72
- - [Replace `null` with `undefined` in props](#replace-null-with-undefined-in-props)
73
- - [Common Errors](#common-errors)
74
- - [Getting warning for `Can't resolve 'react-dom/client'` in React < 18](#getting-warning-for-cant-resolve-react-domclient-in-react--18)
75
- - [Undefined Set](#undefined-set)
76
- - [Using TheRubyRacer](#using-therubyracer)
77
- - [HMR](#hmr)
78
- - [Related Projects](#related-projects)
79
- - [Contributing](#contributing)
80
- - [Supporters](#supporters)
81
-
82
- <!-- END doctoc generated TOC please keep comment here to allow auto update -->
83
-
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)
84
79
 
85
80
  After reading this README file, additional information about React-Rails can be found in the Wiki page:
86
81
  https://github.com/reactjs/React-Rails/wiki
87
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.
88
83
 
89
-
90
- ## Get started with Shakapacker
91
-
92
- _Alternatively, get started with [Sprockets](#use-with-asset-pipeline)_
93
-
94
- 1. Create a new Rails app:
95
- Prevent installing default javascript dependencies by using `--skip-javascript` option:
96
-
97
- ```bash
98
- rails new my-app --skip-javascript
99
- cd my-app
100
- ```
101
-
102
- 2. Install `shakapacker`:
103
- ```bash
104
- bundle add shakapacker --strict
105
- rails shakapacker:install
106
- ```
107
-
108
- 3. Install `react` and some other required npm packages:
109
- ```bash
110
- yarn add react react-dom @babel/preset-react prop-types \
111
- css-loader style-loader mini-css-extract-plugin css-minimizer-webpack-plugin
112
- ```
113
-
114
- Also update the Babel configuration in the `package.json` file:
115
-
116
- ```diff
117
- "babel": {
118
- "presets": [
119
- - "./node_modules/shakapacker/package/babel/preset.js"
120
- + "./node_modules/shakapacker/package/babel/preset.js",
121
- + "@babel/preset-react"
122
- ]
123
- },
124
- ```
125
-
126
- 4. Install `react-rails`:
127
- ```bash
128
- $ bundle add 'react-rails' --strict
129
- $ rails generate react:install
130
- ```
131
-
132
- This gives you:
133
-
134
- - `app/javascript/components/` directory for your React components
135
- - [`ReactRailsUJS`](#ujs) setup in `app/javascript/packs/application.js`
136
- - `app/javascript/packs/server_rendering.js` for [server-side rendering](#server-side-rendering)
137
-
138
- 5. Generate your first component:
139
- ```bash
140
- $ rails g react:component HelloWorld greeting:string
141
- ```
142
-
143
- You can also generate your component in a subdirectory:
144
-
145
- ```bash
146
- $ rails g react:component my_subdirectory/HelloWorld greeting:string
147
- ```
148
-
149
- Note: Your component is added to `app/javascript/components/` by default.
150
-
151
- Note: If your component is in a subdirectory you will append the directory path to your erb component call.
152
-
153
- Example:
154
- ```erb
155
- <%= react_component("my_subdirectory/HelloWorld", { greeting: "Hello from react-rails." }) %>
156
- ```
157
-
158
- 6. [Render it in a Rails view](#view-helper):
159
-
160
- ```erb
161
- <!-- erb: paste this in view -->
162
- <%= react_component("HelloWorld", { greeting: "Hello from react-rails." }) %>
163
- ```
164
-
165
- 7. Lets Start the app:
166
- ```bash
167
- $ rails s
168
- ```
169
- Output: greeting: Hello from react-rails", inspect webpage in your browser to see the change in tag props.
170
-
171
- 8. Run dev server (optional)
172
- In order to run dev server with HMR feature you need to parallely run:
173
-
174
- ```bash
175
- $ ./bin/shakapacker-dev-server
176
- ```
177
-
178
- 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.
179
-
180
- ### Component name
181
-
182
- The component name tells `react-rails` where to load the component. For example:
183
-
184
- `react_component` call | component `require`
185
- -----|-----
186
- `react_component("Item")` | `require("Item")`
187
- `react_component("items/index")` | `require("items/index")`
188
- `react_component("items.Index")` | `require("items").Index`
189
- `react_component("items.Index.Header")` | `require("items").Index.Header`
190
-
191
- This way, you can access top-level, default, or named exports.
192
-
193
- 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`:
194
-
195
- ```js
196
- var myCustomContext = require.context("custom_components", true)
197
- var ReactRailsUJS = require("react_ujs")
198
- // use `custom_components/` for <%= react_component(...) %> calls
199
- ReactRailsUJS.useContext(myCustomContext)
200
- ```
201
-
202
- 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).
203
-
204
- In some cases, having multiple `require.context` entries may be desired. Examples of this include:
205
-
206
- - 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.
207
- - 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:
208
-
209
- ```js
210
- // server_rendering.js
211
- var homepageRequireContext = require.context('homepage', true);
212
- var searchRequireContext = require.context('search', true);
213
- var checkoutRequireContext = require.context('checkout', true);
214
-
215
- var ReactRailsUJS = require('react_ujs');
216
- ReactRailsUJS.useContexts([
217
- homepageRequireContext,
218
- searchRequireContext,
219
- checkoutRequireContext
220
- ]);
221
- ```
222
- ### File naming
223
-
224
- React-Rails supports plenty of file extensions such as: .js, .jsx.js, .js.jsx, .es6.js, .coffee, etcetera!
225
- Sometimes this will cause a stumble when searching for filenames.
226
-
227
- Component File Name | `react_component` call
228
- -----|-----
229
- `app/javascript/components/samplecomponent.js` | `react_component("samplecomponent")`
230
- `app/javascript/components/sample_component.js` | `react_component("sample_component")`
231
- `app/javascript/components/SampleComponent.js` | `react_component("SampleComponent")`
232
- `app/javascript/components/SampleComponent.js.jsx` | Has to be renamed to SampleComponent.jsx, then use `react_component("SampleComponent")`
233
-
234
- ### Typescript support
235
-
236
- ```bash
237
- yarn add typescript @babel/preset-typescript
238
- ```
239
-
240
- Babel won’t perform any type-checking on TypeScript code. To optionally use type-checking run:
241
-
242
- ```bash
243
- yarn add fork-ts-checker-webpack-plugin
244
- ```
245
-
246
- Add `tsconfig.json` with the following content:
247
-
248
- ```json
249
- {
250
- "compilerOptions": {
251
- "declaration": false,
252
- "emitDecoratorMetadata": true,
253
- "experimentalDecorators": true,
254
- "lib": ["es6", "dom"],
255
- "module": "es6",
256
- "moduleResolution": "node",
257
- "sourceMap": true,
258
- "target": "es5",
259
- "jsx": "react",
260
- "noEmit": true
261
- },
262
- "exclude": ["**/*.spec.ts", "node_modules", "vendor", "public"],
263
- "compileOnSave": false
264
- }
265
- ```
266
-
267
- Then modify the webpack config to use it as a plugin:
268
-
269
- ```js
270
- // config/webpack/webpack.config.js
271
- const { webpackConfig, merge } = require("shakapacker");
272
- const ForkTSCheckerWebpackPlugin = require("fork-ts-checker-webpack-plugin");
273
-
274
- module.exports = merge(webpackConfig, {
275
- plugins: [new ForkTSCheckerWebpackPlugin()],
276
- });
277
- ```
278
-
279
- 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:
280
-
281
- ```ruby
282
- config.react.server_renderer_extensions = ["jsx", "js", "tsx", "ts"]
283
- ```
284
-
285
- ### Test component
286
-
287
- You can use `assert_react_component` to test component render:
288
-
289
- ```erb
290
- <!-- app/views/welcome/index.html.erb -->
291
-
292
- <%= react_component("HelloWorld", { greeting: "Hello from react-rails.", info: { name: "react-rails" } }, { class: "hello-world" }) %>
293
- ```
294
-
295
- ```rb
296
- class WelcomeControllerTest < ActionDispatch::IntegrationTest
297
- test 'assert_react_component' do
298
- get "/welcome"
299
- assert_equal 200, response.status
300
-
301
- # assert rendered react component and check the props
302
- assert_react_component "HelloWorld" do |props|
303
- assert_equal "Hello from react-rails.", props[:greeting]
304
- assert_equal "react-rails", props[:info][:name]
305
- assert_select "[class=?]", "hello-world"
306
- end
307
-
308
- # or just assert component rendered
309
- assert_react_component "HelloWorld"
310
- end
311
- end
312
- ```
313
-
314
- ## Use with Asset Pipeline
315
-
316
- `react-rails` provides a pre-bundled React.js & a UJS driver to the Rails asset pipeline. Get started by adding the `react-rails` gem:
317
-
318
- ```ruby
319
- gem 'react-rails'
320
- ```
321
-
322
- And then install the react generator:
323
-
324
- ```
325
- $ rails g react:install
326
- ```
327
-
328
- Then restart your development server.
329
-
330
- This will:
331
-
332
- - add some `//= require`s to `application.js`
333
- - add a `components/` directory for React components
334
- - add `server_rendering.js` for [server-side rendering](#server-side-rendering)
335
-
336
- Now, you can create React components in `.jsx` files:
337
-
338
- ```JSX
339
- // app/assets/javascripts/components/post.jsx
340
-
341
- window.Post = createReactClass({
342
- render: function() {
343
- return <h1>{this.props.title}</h1>
344
- }
345
- })
346
-
347
- // or, equivalent:
348
- class Post extends React.Component {
349
- render() {
350
- return <h1>{this.props.title}</h1>
351
- }
352
- }
353
- ```
354
-
355
- Then, you can render those [components in views](#view-helper):
356
-
357
- ```erb
358
- <%= react_component("Post", {title: "Hello World"}) %>
359
- ```
360
-
361
- Components must be accessible from the top level, but they may be namespaced, for example:
362
-
363
- ```erb
364
- <%= react_component("Comments.NewForm", {post_id: @post.id}) %>
365
- <!-- looks for `window.Comments.NewForm` -->
366
- ```
367
-
368
- ### Custom JSX Transformer
369
-
370
- `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:
371
-
372
- - `#initialize(options)`, where options is the value passed to `config.react.jsx_transform_options`
373
- - `#transform(code_string)` to return a string of transformed code
374
-
375
- `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`).
376
-
377
- #### Transform Plugin Options
378
-
379
- To supply additional transform plugins to your JSX Transformer, assign them to `config.react.jsx_transform_options`
380
-
381
- `react-rails` uses the Babel version of the `babel-source` gem.
382
-
383
- For example, to use `babel-plugin-transform-class-properties` :
384
-
385
- config.react.jsx_transform_options = {
386
- optional: ['es7.classProperties']
387
- }
388
-
389
- ### React.js versions
390
-
391
- `//= require react` brings `React` into your project.
392
-
393
- By default, React's [development version] is provided to `Rails.env.development`. You can override the React build with a config:
394
-
395
- ```ruby
396
- # Here are the defaults:
397
- # config/environments/development.rb
398
- MyApp::Application.configure do
399
- config.react.variant = :development
400
- end
401
-
402
- # config/environments/production.rb
403
- MyApp::Application.configure do
404
- config.react.variant = :production
405
- end
406
- ```
407
-
408
- 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`
409
-
410
-
411
- ## View Helper
412
-
413
- `react-rails` includes a view helper and an [unobtrusive JavaScript driver](#ujs) which work together to put React components on the page.
414
-
415
- The view helper (`react_component`) puts a `div` on the page with the requested component class & props. For example:
416
-
417
- ```erb
418
- <%= react_component('HelloMessage', name: 'John') %>
419
- <!-- becomes: -->
420
- <div data-react-class="HelloMessage" data-react-props="{&quot;name&quot;:&quot;John&quot;}"></div>
421
- ```
422
-
423
- On page load, the [`react_ujs` driver](#ujs) will scan the page and mount components using `data-react-class`
424
- and `data-react-props`.
425
-
426
- The view helper's signature is:
427
-
428
- ```ruby
429
- react_component(component_class_name, props={}, html_options={})
430
- ```
431
-
432
- - `component_class_name` is a string which identifies a component. See [getConstructor](#getconstructor) for details.
433
- - `props` is either:
434
- - an object that responds to `#to_json`; or
435
- - an already-stringified JSON object (see [JBuilder note](#use-with-jbuilder) below).
436
- - `html_options` may include:
437
- - `tag:` to use an element other than a `div` to embed `data-react-class` and `data-react-props`.
438
- - `prerender: true` to render the component on the server.
439
- - `camelize_props` to [transform a props hash](#camelize-props)
440
- - `**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).
441
-
442
-
443
- #### Custom View Helper
444
-
445
- `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:
446
-
447
- - `#react_component(name, props = {}, options = {}, &block)` to return a string to inject into the Rails view
448
- - `#setup(controller_instance)`, called when the helper is initialized at the start of the request
449
- - `#teardown(controller_instance)`, called at the end of the request
450
-
451
- `react-rails` provides one implementation, `React::Rails::ComponentMount`.
452
-
453
- ## UJS
454
-
455
- `react-rails`'s JavaScript is available as `"react_ujs"` in the asset pipeline or from NPM. It attaches itself to the window as `ReactRailsUJS`.
456
-
457
- ### Mounting & Unmounting
458
-
459
- Usually, `react-rails` mounts & unmounts components automatically as described in [Event Handling](#event-handling) below.
460
-
461
- You can also mount & unmount components from `<%= react_component(...) %>` tags using UJS:
462
-
463
- ```js
464
- // Mount all components on the page:
465
- ReactRailsUJS.mountComponents()
466
- // Mount components within a selector:
467
- ReactRailsUJS.mountComponents(".my-class")
468
- // Mount components within a specific node:
469
- ReactRailsUJS.mountComponents(specificDOMnode)
470
-
471
- // Unmounting works the same way:
472
- ReactRailsUJS.unmountComponents()
473
- ReactRailsUJS.unmountComponents(".my-class")
474
- ReactRailsUJS.unmountComponents(specificDOMnode)
475
- ```
476
-
477
- You can use this when the DOM is modified by AJAX calls or modal windows.
478
-
479
- ### Event Handling
480
-
481
- `ReactRailsUJS` checks for various libraries to support their page change events:
482
-
483
- - `Turbolinks`
484
- - `pjax`
485
- - `jQuery`
486
- - Native DOM events
487
-
488
- `ReactRailsUJS` will automatically mount components on `<%= react_component(...) %>` tags and unmount them when appropriate.
489
-
490
- If you need to re-detect events, you can call `detectEvents`:
491
-
492
- ```js
493
- // Remove previous event handlers and add new ones:
494
- ReactRailsUJS.detectEvents()
495
- ```
496
-
497
- 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.
498
-
499
- 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:
500
-
501
- ```js
502
- // Order is particular. First start Turbolinks:
503
- Turbolinks.start();
504
- // Add Turbolinks to the global namespace:
505
- window.Turbolinks = Turbolinks;
506
- // Remove previous event handlers and add new ones:
507
- ReactRailsUJS.detectEvents();
508
- // (Optional) Clean up global namespace:
509
- delete window.Turbolinks;
510
- ```
511
-
512
- ### `getConstructor`
513
-
514
- Components are loaded with `ReactRailsUJS.getConstructor(className)`. This function has two default implementations, depending on if you're using the asset pipeline or Shakapacker:
515
-
516
- - On the asset pipeline, it looks up `className` in the global namespace (`ReactUJS.constructorFromGlobal`).
517
- - 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`).
518
-
519
- You can override this function to customize the mapping of name-to-constructor. [Server-side rendering](#server-side-rendering) also uses this function.
520
-
521
- For example, the fallback behavior of
522
- `ReactUJS.constructorFromRequireContextWithGlobalFallback` can sometimes make
523
- server-side rendering errors hard to debug as it will swallow the original error
524
- (more info
525
- [here](https://github.com/reactjs/react-rails/issues/264#issuecomment-552326663)).
526
- `ReactUJS.constructorFromRequireContext` is provided for this reason. You can
527
- use it like so:
528
-
529
- ```js
530
- // Replaces calls to `ReactUJS.useContext`
531
- ReactUJS.getConstructor = ReactUJS.constructorFromRequireContext(require.context('components', true));
532
- ```
533
-
534
- ## Server-Side Rendering
535
-
536
- You can render React components inside your Rails server with `prerender: true`:
537
-
538
- ```erb
539
- <%= react_component('HelloMessage', {name: 'John'}, {prerender: true}) %>
540
- <!-- becomes: -->
541
- <div data-react-class="HelloMessage" data-react-props="{&quot;name&quot;:&quot;John&quot;}">
542
- <h1>Hello, John!</h1>
543
- </div>
544
- ```
545
-
546
- _(It will also be mounted by the [UJS](#ujs) on page load.)_
547
-
548
- Server rendering is powered by [`ExecJS`](https://github.com/rails/execjs) and subject to some requirements:
549
-
550
- - `react-rails` must load your code. By convention, it uses `server_rendering.js`, which was created
551
- by the install task. This file must include your components _and_ their dependencies (eg, Underscore.js).
552
- - Requires separate compilations for server & client bundles (see [Webpack config](https://github.com/reactjs/react-rails/tree/master/test/dummy/config/webpack))
553
- - Your code can't reference `document` or `window`. Prerender processes don't have access to `document` or `window`,
554
- so jQuery and some other libs won't work in this environment :(
555
-
556
- `ExecJS` supports many backends. CRuby users will get the best performance from [`mini_racer`](https://github.com/discourse/mini_racer#performance).
557
-
558
- #### Configuration
559
-
560
- 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`.
561
-
562
- These are the default configurations:
563
-
564
- ```ruby
565
- # config/application.rb
566
- # These are the defaults if you don't specify any yourself
567
- module MyApp
568
- class Application < Rails::Application
569
- # Settings for the pool of renderers:
570
- config.react.server_renderer_pool_size ||= 1 # ExecJS doesn't allow more than one on MRI
571
- config.react.server_renderer_timeout ||= 20 # seconds
572
- config.react.server_renderer = React::ServerRendering::BundleRenderer
573
- config.react.server_renderer_options = {
574
- files: ["server_rendering.js"], # files to load for prerendering
575
- replay_console: true, # if true, console.* will be replayed client-side
576
- }
577
- # Changing files matching these dirs/exts will cause the server renderer to reload:
578
- config.react.server_renderer_extensions = ["jsx", "js"]
579
- config.react.server_renderer_directories = ["/app/assets/javascripts", "/app/javascript/"]
580
- end
581
- end
582
- ```
583
-
584
- #### JavaScript State
585
-
586
- 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.
587
-
588
- To manage state, you have a couple options:
589
-
590
- - Make a custom renderer with `#before_render` / `#after_render` hooks as [described below](#custom-server-renderer)
591
- - Use `per_request_react_rails_prerenderer` to manage state for a whole controller action.
592
-
593
- To check out a renderer for the duration of a controller action, call the `per_request_react_rails_prerenderer` helper in the controller class:
594
-
595
- ```ruby
596
- class PagesController < ApplicationController
597
- # Use the same React server renderer for the entire request:
598
- per_request_react_rails_prerenderer
599
- end
600
- ```
601
-
602
- Then, you can access the ExecJS context directly with `react_rails_prerenderer.context`:
603
-
604
- ```ruby
605
- def show
606
- react_rails_prerenderer # => #<React::ServerRendering::BundleRenderer>
607
- react_rails_prerenderer.context # => #<ExecJS::Context>
608
-
609
- # Execute arbitrary JavaScript code
610
- # `self` is the global context
611
- react_rails_prerenderer.context.exec("self.Store.setup()")
612
- render :show
613
- react_rails_prerenderer.context.exec("self.Store.teardown()")
614
- end
615
- ```
616
-
617
- `react_rails_prerenderer` may also be accessed in before- or after-actions.
618
-
619
- #### Custom Server Renderer
620
-
621
- `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:
622
-
623
- - `#initialize(options={})`, which accepts the hash from `config.react.server_renderer_options`
624
- - `#render(component_name, props, prerender_options)` to return a string of HTML
625
-
626
- `react-rails` provides two renderer classes: `React::ServerRendering::ExecJSRenderer` and `React::ServerRendering::BundleRenderer`.
627
-
628
- `ExecJSRenderer` offers two other points for extension:
629
-
630
- - `#before_render(component_name, props, prerender_options)` to return a string of JavaScript to execute _before_ calling `React.render`
631
- - `#after_render(component_name, props, prerender_options)` to return a string of JavaScript to execute _after_ calling `React.render`
632
-
633
- Any subclass of `ExecJSRenderer` may use those hooks (for example, `BundleRenderer` uses them to handle `console.*` on the server).
634
-
635
- ## Controller Actions
636
-
637
- Components can also be server-rendered directly from a controller action with the custom `component` renderer. For example:
638
-
639
- ```ruby
640
- class TodoController < ApplicationController
641
- def index
642
- @todos = Todo.all
643
- render component: 'TodoList', props: { todos: @todos }, tag: 'span', class: 'todo'
644
- end
645
- end
646
- ```
647
-
648
- 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}`.
649
-
650
- Prerendering is set to `true` by default, but can be turned off with `prerender: false`.
651
-
652
- ## Component Generator
653
-
654
- You can generate a new component file with:
655
-
656
- ```sh
657
- rails g react:component ComponentName prop1:type prop2:type ... [options]
658
- ```
659
-
660
- For example,
661
-
662
- ```sh
663
- rails g react:component Post title:string published:bool published_by:instanceOf{Person}
664
- ```
665
-
666
- would generate:
667
-
668
- ```JSX
669
- var Post = createReactClass({
670
- propTypes: {
671
- title: PropTypes.string,
672
- published: PropTypes.bool,
673
- publishedBy: PropTypes.instanceOf(Person)
674
- },
675
-
676
- render: function() {
677
- return (
678
- <React.Fragment>
679
- Title: {this.props.title}
680
- Published: {this.props.published}
681
- Published By: {this.props.publishedBy}
682
- </React.Fragment>
683
- );
684
- }
685
- });
686
- ```
687
-
688
- The generator also accepts options:
689
-
690
- - `--es6`: generates a function component
691
- - `--coffee`: use CoffeeScript
692
-
693
- For example,
694
-
695
- ```sh
696
- rails g react:component ButtonComponent title:string --es6
697
- ```
698
-
699
- would generate:
700
-
701
- ```jsx
702
- import React from "react"
703
- import PropTypes from "prop-types"
704
-
705
- function ButtonComponent(props) {
706
- return (
707
- <React.Fragment>
708
- Title: {this.props.title}
709
- </React.Fragment>
710
- );
711
- }
712
-
713
- ButtonComponent.propTypes = {
714
- title: PropTypes.string
715
- };
716
-
717
- export default ButtonComponent
718
- ```
719
-
720
- **Note:** In a Shakapacker project, es6 template is the default template in the generator.
721
-
722
- Accepted PropTypes are:
723
-
724
- - Plain types: `any`, `array`, `bool`, `element`, `func`, `number`, `object`, `node`, `shape`, `string`
725
- - `instanceOf` takes an optional class name in the form of `instanceOf{className}`.
726
- - `oneOf` behaves like an enum, and takes an optional list of strings in the form of `'name:oneOf{one,two,three}'`.
727
- - `oneOfType` takes an optional list of react and custom types in the form of `'model:oneOfType{string,number,OtherType}'`.
728
-
729
- Note that the arguments for `oneOf` and `oneOfType` must be enclosed in single quotes
730
- to prevent your terminal from expanding them into an argument list.
731
-
732
- #### Use with JBuilder
733
-
734
- If you use Jbuilder to pass a JSON string to `react_component`, make sure your JSON is a stringified hash,
735
- not an array. This is not the Rails default -- you should add the root node yourself. For example:
736
-
737
- ```ruby
738
- # BAD: returns a stringified array
739
- json.array!(@messages) do |message|
740
- json.extract! message, :id, :name
741
- json.url message_url(message, format: :json)
742
- end
743
-
744
- # GOOD: returns a stringified hash
745
- json.messages(@messages) do |message|
746
- json.extract! message, :id, :name
747
- json.url message_url(message, format: :json)
748
- end
749
- ```
750
-
751
- ### Camelize Props
752
-
753
- You can configure `camelize_props` option:
754
-
755
- ```ruby
756
- MyApp::Application.configure do
757
- config.react.camelize_props = true # default false
758
- end
759
- ```
760
-
761
- Now, Ruby hashes given to `react_component(...)` as props will have their keys transformed from _underscore_- to _camel_-case, for example:
762
-
763
- ```ruby
764
- { all_todos: @todos, current_status: @status }
765
- # becomes:
766
- { "allTodos" => @todos, "currentStatus" => @status }
767
- ```
768
-
769
- You can also specify this option in `react_component`:
770
-
771
- ```erb
772
- <%= react_component('HelloMessage', {name: 'John'}, {camelize_props: true}) %>
773
- ```
774
-
775
- ### Changing Component Templates
776
-
777
- To make simple changes to Component templates, copy the respective template file to your Rails project at `lib/templates/react/component/template_filename`.
778
-
779
- 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.
780
-
781
- ## Upgrading
782
-
783
- ### 2.7 to 3.0
784
- - Keep your `react_ujs` up to date: `yarn upgrade`
785
- - **Drop support for Webpacker:** Before any ReactRails upgrade, make sure upgrading from Webpacker to Shakapacker 7. For more information check out Shakapacker
786
- - **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.
787
-
788
- ### 2.3 to 2.4
789
-
790
- Keep your `react_ujs` up to date, `yarn upgrade`
791
-
792
- 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.
793
-
794
- If you need to make changes in your components for the prebundled react, see the migration docs here:
795
-
796
- - https://reactjs.org/blog/2016/11/16/react-v15.4.0.html
797
- - https://reactjs.org/blog/2017/04/07/react-v15.5.0.html
798
- - https://reactjs.org/blog/2017/06/13/react-v15.6.0.html
799
-
800
-
801
- For the vast majority of cases this will get you most of the migration:
802
- - global find+replace `React.Prop` -> `Prop`
803
- - add `import PropTypes from 'prop-types'` (Webpacker only)
804
- - re-run `bundle exec rails webpacker:install:react` to update npm packages (Webpacker only)
805
-
806
- ## Other features
807
-
808
- ### Replace `null` with `undefined` in props
809
-
810
- React-Rails converts `nil` to `null` while parsing props from Ruby to JavaScript. Optionally, you can configure React-Rails to parse `nil` values to `undefined` as per the following:
811
-
812
- ```ruby
813
- # config/application.rb
814
- module TheAppName
815
- class Application < Rails::Application
816
- # ...
817
- # Set to true to convert null values in props into undefined
818
- config.react.null_to_undefined_props = true
819
- # ...
820
- end
821
- end
822
- ```
823
-
824
- More information in: [discussion#1272](https://github.com/reactjs/react-rails/discussions/1272).
825
-
826
- ## Common Errors
827
- ### Getting warning for `Can't resolve 'react-dom/client'` in React < 18
828
-
829
- 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`:
830
-
831
- ```diff
832
- - const { webpackConfig } = require('shakapacker')
833
- + const { webpackConfig, merge } = require('shakapacker')
834
-
835
- +const ignoreWarningsConfig = {
836
- + ignoreWarnings: [/Module not found: Error: Can't resolve 'react-dom\/client'/],
837
- +};
838
-
839
- - module.exports = webpackConfig
840
- + module.exports = merge({}, webpackConfig, ignoreWarningsConfig)
841
- ```
842
-
843
- ### Undefined Set
844
- ```
845
- ExecJS::ProgramError (identifier 'Set' undefined):
846
-
847
- (execjs):1
848
- ```
849
- If you see any variation of this issue, see [Using TheRubyRacer](#using-therubyracer)
850
-
851
-
852
- ### Using TheRubyRacer
853
- 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.
854
-
855
- 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.
856
-
857
- ### HMR
858
-
859
- 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.
860
-
861
- One caveat is that currently you [cannot Server-Side Render along with HMR](https://github.com/reactjs/react-rails/issues/925#issuecomment-415469572).
862
-
863
84
  ## Related Projects
864
85
 
865
86
  - [webpacker-react](https://github.com/renchap/webpacker-react): Integration of React with Rails utilizing Webpack with Hot Module Replacement (HMR).
@@ -879,7 +100,7 @@ By contributing to React-Rails, you agree to abide by the [code of conduct](http
879
100
 
880
101
  You can always help by submitting patches or triaging issues. Even offering reproduction steps to issues is incredibly helpful!
881
102
 
882
- ## Supporters
103
+ # Supporters
883
104
 
884
105
  The following companies support the development of this and other open-source projects maintained by ShakaCode by providing licenses to the ShakaCode team. ShakaCode stands by the usefulness of these products!
885
106
 
@@ -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 %>
@@ -56,10 +56,7 @@ module React
56
56
  unless prerender_options == :static
57
57
  html_options[:data].tap do |data|
58
58
  data[:react_class] = name
59
- data[:react_props] = props_to_json(
60
- props,
61
- null_to_undefined: Dummy::Application.config.react.null_to_undefined_props
62
- )
59
+ data[:react_props] = (props.is_a?(String) ? props : props.to_json)
63
60
  data[:hydrate] = "t" if prerender_options
64
61
 
65
62
  num_components = @cache_ids.count { |c| c.start_with? name }
@@ -70,17 +67,6 @@ module React
70
67
  html_options
71
68
  end
72
69
 
73
- def props_to_json(props, options = { null_to_undefined: false })
74
- return props if props.is_a?(String)
75
- return props.to_json unless options[:null_to_undefined]
76
-
77
- # This regex matches key:value with null values while ensuing no string with similar
78
- # pattern gets matched. It doesn't include null values in arrays.
79
- props.to_json
80
- .gsub(/([^\\]":)null([,}\]])/, '\1undefined\2') # match simple null values
81
- .gsub(/([^\\]":(\[[^\\"]+,|\[))null([,\]])/, '\1undefined\3') # Match nulls in array
82
- end
83
-
84
70
  def rendered_tag(html_options, &block)
85
71
  html_tag = html_options[:tag] || :div
86
72
 
@@ -12,7 +12,6 @@ module React
12
12
  config.react.jsx_transformer_class = nil # defaults to BabelTransformer
13
13
  config.react.camelize_props = false # pass in an underscored hash but get a camelized hash
14
14
  config.react.sprockets_strategy = nil # how to attach JSX to the asset pipeline (or `false` for none)
15
- config.react.null_to_undefined_props = false # Set to true to convert null values in props into undefined
16
15
 
17
16
  # Server rendering:
18
17
  config.react.server_renderer_pool_size = 1 # increase if you're on JRuby
@@ -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.0"
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.0
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-15 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