Skip to content

Commit ebf7e61

Browse files
committed
Modify register API to accept renderer functions (shakacode#581)
Made the following changes to the node package: * ComponentRegistry.js: Modified register to detect generator functions with three arguments. Set the isRenderer key to true for these functions. * clientStartup.js: Added logic to delegate to renderer functions. * createReactElement.js: Now accepts an object instead of a component name. * serverRenderReactComponent.js: Throws an error if attempting to render a renderer function. * ReactOnRails.js: Change render function to call createReactElement with the component object. Doc changes: * README.md: Added section about renderer function under the section on generator functions. Moved the section on generator functions from the 'ReactOnRails View Helpers API' section to the 'Globally Exposing Your React Components' section. * Added a file code-splitting.md that describes how to use renderer functions to do code splitting with server rendering. Tests: * ComponentRegistry.test.js: Modified existing test cases to expect the isRenderer key to be false. Added a few test cases related to renderer functions. * serverRenderReactComponent.test.js: Show that an error gets thrown if trying to server render with a renderer function. * spec/dummy: Added two examples using rendering functions, one of which implements code splitting. Added three test to integration_spec.rb. Resolves: shakacode#477
1 parent 03c5e96 commit ebf7e61

24 files changed

+548
-35
lines changed

CHANGELOG.md

+6-1
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,10 @@ Contributors: please follow the recommendations outlined at [keepachangelog.com]
55

66
## [Unreleased]
77

8+
## [6.3.0]
9+
##### Added
10+
- Modify register API to allow registration of renderers, allowing a user to manually render their app to the DOM [#581](https://github.com/shakacode/react_on_rails/pull/581) by [jtibbertsma](https://github.com/jtibbertsma).
11+
812
## [6.2.1] - 2016-11-19
913
- Removed unnecesary passing of context in the HelloWorld Container example and basic generator. [#612](https://github.com/shakacode/react_on_rails/pull/612) by [justin808](https://github.com/justin808)
1014

@@ -383,7 +387,8 @@ Best done with Object destructing:
383387
##### Fixed
384388
- Fix several generator related issues.
385389

386-
[Unreleased]: https://github.com/shakacode/react_on_rails/compare/6.2.1...master
390+
[Unreleased]: https://github.com/shakacode/react_on_rails/compare/6.3.0...master
391+
[6.3.0]: https://github.com/shakacode/react_on_rails/compare/6.2.1...6.3.0
387392
[6.2.1]: https://github.com/shakacode/react_on_rails/compare/6.2.0...6.2.1
388393
[6.2.0]: https://github.com/shakacode/react_on_rails/compare/6.1.2...6.2.0
389394
[6.1.2]: https://github.com/shakacode/react_on_rails/compare/6.1.1...6.1.2

README.md

+12-5
Original file line numberDiff line numberDiff line change
@@ -310,6 +310,14 @@ You may want different initialization for your server rendered components. For e
310310

311311
If you do want different code to run, you'd setup a separate webpack compilation file and you'd specify a different, server side entry file. ex. 'serverHelloWorldApp.jsx'. Note, you might be initializing HelloWorld with version specialized for server rendering.
312312

313+
#### Generator Functions
314+
Why would you create a function that returns a React component? For example, you may want the ability to use the passed-in props to initialize a redux store or setup react-router. Or you may want to return different components depending on what's in the props. ReactOnRails will automatically detect a registered generator function.
315+
316+
#### Renderer Functions
317+
A renderer function is a generator function that accepts three arguments: `(props, railsContext, domNodeId) => { ... }`. Instead of returning a React component, a renderer is responsible for calling `ReactDOM.render` to manually render a React component into the dom. Why would you want to call `ReactDOM.render` yourself? One possible use case is [code splitting](docs/additional-reading/code-splitting.md).
318+
319+
Renderer functions are not meant to be used on the server, since there's no DOM on the server. Instead, use a generator function. Attempting to server render with a renderer function will cause an error.
320+
313321
## ReactOnRails View Helpers API
314322
Once the bundled files have been generated in your `app/assets/webpack` folder and you have exposed your components globally, you will want to run your code in your Rails views using the included helper method.
315323

@@ -327,7 +335,7 @@ react_component(component_name,
327335
html_options: {})
328336
```
329337

330-
+ **component_name:** Can be a React component, created using a ES6 class, or `React.createClass`, or a generator function that returns a React component.
338+
+ **component_name:** Can be a React component, created using a ES6 class, or `React.createClass`, a generator function that returns a React component, or a renderer function that manually renders a React component to the dom (client side only).
331339
+ **options:**
332340
+ **props:** Ruby Hash which contains the properties to pass to the react object, or a JSON string. If you pass a string, we'll escape it for you.
333341
+ **prerender:** enable server-side rendering of component. Set to false when debugging!
@@ -365,9 +373,6 @@ Note, you don't need to separately initialize your redux store. However, it's re
365373
1. You want to have multiple components that access the same store.
366374
2. You want to place the props to hydrate the client side stores at the very end of your HTML so that the browser can render all earlier HTML first. This is particularly useful if your props will be large.
367375

368-
### Generator Functions
369-
Why would you create a function that returns a React component? For example, you may want the ability to use the passed-in props to initialize a redux store or setup react-router. Or you may want to return different components depending on what's in the props. ReactOnRails will automatically detect a registered generator function.
370-
371376
### server_render_js
372377
`server_render_js(js_expression, options = {})`
373378

@@ -439,7 +444,7 @@ See [ReactOnRails JavaScript API](docs/api/javascript-api.md).
439444

440445
Rails has built-in protection for Cross-Site Request Forgery (CSRF), see [Rails Documentation](http://guides.rubyonrails.org/security.html#cross-site-request-forgery-csrf). To nicely utilize this feature in JavaScript requests, React on Rails is offerring two helpers that can be used as following for POST, PUT or DELETE requests:
441446

442-
```
447+
```js
443448
import ReactOnRails from 'react-on-rails';
444449

445450
// reads from DOM csrf token generated by Rails in <%= csrf_meta_tags %>
@@ -456,6 +461,7 @@ If you are using [jquery-ujs](https://github.com/rails/jquery-ujs) for AJAX call
456461

457462
1. [React on Rails docs for react-router](docs/additional-reading/react-router.md)
458463
1. Examples in [spec/dummy/app/views/react_router](spec/dummy/app/views/react_router) and follow to the JavaScript code in the [spec/dummy/client/app/startup/ServerRouterApp.jsx](spec/dummy/client/app/startup/ServerRouterApp.jsx).
464+
1. [Code Splitting docs](docs/additional-reading/code-splitting.md) for information about how to set up code splitting for server rendered routes.
459465

460466
## Deployment
461467
* Version 6.0 puts the necessary precompile steps automatically in the rake precompile step. You can, however, disable this by setting certain values to nil in the [config/initializers/react_on_rails.rb](spec/dummy/config/initializers/react_on_rails.rb).
@@ -486,6 +492,7 @@ Node.js can be used as the backend for server-side rendering instead of [execJS]
486492
+ [Developing with the Webpack Dev Server](docs/additional-reading/webpack-dev-server.md)
487493
+ [Node Server Rendering](docs/additional-reading/node-server-rendering.md)
488494
+ [Server Rendering Tips](docs/additional-reading/server-rendering-tips.md)
495+
+ [Code Splitting](docs/additional-reading/code-splitting.md)
489496

490497
+ **Development**
491498
+ [React on Rails Basic Installation Tutorial](docs/tutorial.md) ([live demo](https://hello-react-on-rails.herokuapp.com))
+155
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,155 @@
1+
# Code Splitting
2+
3+
What is code splitting? From the webpack documentation:
4+
5+
> For big web apps it’s not efficient to put all code into a single file, especially if some blocks of code are only required under some circumstances. Webpack has a feature to split your codebase into “chunks” which are loaded on demand. Some other bundlers call them “layers”, “rollups”, or “fragments”. This feature is called “code splitting”.
6+
7+
## Server Rendering and Code Splitting
8+
9+
Let's say you're requesting a page that needs to fetch a code chunk from the server before it's able to render. If you do all your rendering on the client side, you don't have to do anything special. However, if the page is rendered on the server, you'll find that React will spit out the following error:
10+
11+
> Warning: React attempted to reuse markup in a container but the checksum was invalid. This generally means that you are using server rendering and the markup generated on the server was not what the client was expecting. React injected new markup to compensate which works but you have lost many of the benefits of server rendering. Instead, figure out why the markup being generated is different on the client or server:
12+
13+
> (client) <!-- react-empty: 1 -
14+
15+
> (server) <div data-reactroot="
16+
<!--This comment is here because the comment beginning on line 13 messes up Sublime's markdown parsing-->
17+
18+
Different markup is generated on the client than on the server. Why does this happen? When you register a component or generator function with `ReactOnRails.register`, react on rails will render the component as soon as the page loads. However, react-router renders a comment while waiting for the code chunk to be fetched from the server. This means that react will tear all of the server rendered code out of the DOM, and then rerender it a moment later once the code chunk arrives from the server, defeating most of the purpose of server rendering.
19+
20+
### The solution
21+
22+
To prevent this, you have to wait until the code chunk is fetched before doing the initial render on the client side. To accomplish this, react on rails allows you to register a renderer. This works just like registering a generator function, except that the function you pass takes three arguments: `renderer(props, railsContext, domNodeId)`, and is responsible for calling `ReactDOM.render` to render the component to the DOM. React on rails will automatically detect when a generator function takes three arguments, and will not call `ReactDOM.render`, instead allowing you to control the initial render yourself.
23+
24+
Here's an example of how you might use this in practice:
25+
26+
#### page.html.erb
27+
```erb
28+
<%= react_component("NavigationApp", prerender: true) %>
29+
<%= react_component("RouterApp", prerender: true) %>
30+
<%= redux_store_hydration_data %>
31+
```
32+
33+
#### clientRegistration.js
34+
```js
35+
import ReactOnRails from 'react-on-rails';
36+
import NavigationApp from './NavigationApp';
37+
38+
// Note that we're importing a different RouterApp that in serverRegistration.js
39+
// Renderer functions should not be used on the server, because there is no DOM.
40+
import RouterApp from './RouterAppRenderer';
41+
import applicationStore from '../store/applicationStore';
42+
43+
ReactOnRails.registerStore({applicationStore});
44+
ReactOnRails.register({
45+
NavigationApp,
46+
RouterApp,
47+
});
48+
```
49+
50+
#### serverRegistration.js
51+
```js
52+
import ReactOnRails from 'react-on-rails';
53+
import NavigationApp from './NavigationApp';
54+
55+
// Note that we're importing a different RouterApp that in clientRegistration.js
56+
import RouterApp from './RouterAppServer';
57+
import applicationStore from '../store/applicationStore';
58+
59+
ReactOnRails.registerStore({applicationStore});
60+
ReactOnRails.register({
61+
NavigationApp,
62+
RouterApp,
63+
});
64+
```
65+
Note that you should not register a renderer on the server, since there won't be a domNodeId when we're server rendering. Note that the `RouterApp` imported by `serverRegistration.js` is from a different file. For an example of how to set up an app for server rendering, see the [react router docs](react-router.md).
66+
67+
#### RouterAppRenderer.jsx
68+
```jsx
69+
import ReactOnRails from 'react-on-rails';
70+
import React from 'react';
71+
import ReactDOM from 'react-dom';
72+
import Router from 'react-router/lib/Router';
73+
import match from 'react-router/lib/match';
74+
import browserHistory from 'react-router/lib/browserHistory';
75+
import { Provider } from 'react-redux';
76+
77+
import routes from '../routes/routes';
78+
79+
80+
const RouterAppRenderer = (props, railsContext, domNodeId) => {
81+
const store = ReactOnRails.getStore('applicationStore');
82+
const history = browserHistory;
83+
84+
match({ history, routes }, (error, redirectionLocation, renderProps) => {
85+
if (error) {
86+
throw error;
87+
}
88+
89+
const reactElement = (
90+
<Provider store={store}>
91+
<Router {...renderProps} />
92+
</Provider>
93+
);
94+
95+
ReactDOM.render(reactElement, document.getElementById(domNodeId));
96+
});
97+
};
98+
99+
export default RouterAppRenderer;
100+
```
101+
102+
What's going on in this example is that we're putting the rendering code in the callback passed to `match`. The effect is that the client render doesn't happen until the code chunk gets fetched from the server, preventing the client/server checksum mismatch.
103+
104+
The idea is that match from react-router is async; it fetches the component using the getComponent method that you provide with the route definition, and then passes the props to the callback that are needed to do the complete render. Then we do the first render inside of the callback, so that the first render is the same as the server render.
105+
106+
The server render matches the deferred render because the server bundle is a single file, and so it doesn't need to wait for anything to be fetched.
107+
108+
### Working Example
109+
110+
There's an implemented example of code splitting in the `spec/dummy` folder of this repository.
111+
112+
See:
113+
114+
- [spec/dummy/client/app/startup/clientRegistration.jsx](../../spec/dummy/client/app/startup/clientRegistration.jsx)
115+
- [spec/dummy/client/app/startup/serverRegistration.jsx](../../spec/dummy/client/app/startup/serverRegistration.jsx)
116+
- [spec/dummy/client/app/startup/DeferredRenderAppRenderer.jsx](../../spec/dummy/client/app/startup/DeferredRenderAppRenderer.jsx) <-- Code splitting implemented here
117+
- [spec/dummy/client/app/startup/DeferredRenderAppServer.jsx](../../spec/dummy/client/app/startup/DeferredRenderAppServer.jsx)
118+
- [spec/dummy/client/app/components/DeferredRender.jsx](../../spec/dummy/client/app/components/DeferredRender.jsx)
119+
- [spec/dummy/client/app/components/DeferredRenderAsyncPage.jsx](../../spec/dummy/client/app/components/DeferredRenderAsyncPage.jsx)
120+
121+
### Caveats
122+
123+
If you're going to try to do code splitting with server rendered routes, you'll probably need to use seperate route definitions for client and server to prevent code splitting from happening for the server bundle. The server bundle should be one file containing all the JavaScript code. This will require you to have seperate webpack configurations for client and server.
124+
125+
The reason is we do server rendering with ExecJS, which is not capable of doing anything asynchronous. It would be impossible to asyncronously fetch a code chunk while server rendering. See [this issue](https://github.com/shakacode/react_on_rails/issues/477) for a discussion.
126+
127+
Also, do not attempt to register a renderer on the server. Instead, register either a generator function or a component. If you register a renderer in the server bundle, you'll get an error when react on rails tries to server render the component.
128+
129+
## How does Webpack know where to find my code chunks?
130+
131+
Add the following to the output key of your webpack config:
132+
133+
```js
134+
config = {
135+
output: {
136+
publicPath: '/assets/',
137+
}
138+
};
139+
```
140+
141+
This causes Webpack to prepend the code chunk filename with `/assets/` in the request url. The react on rails sets up the webpack config to put webpack bundles in `app/assets/javascripts/webpack`, and modifies `config/initializers/assets.rb` so that rails detects the bundles. This means that when we prepend the request url with `/assets/`, rails will know what webpack is asking for.
142+
143+
See [rails-assets.md](./rails-assets.md) to learn more about static assets.
144+
145+
If you forget to set the public path, webpack will request the code chunk at `/{filename}`. This will cause the request to be handled by the Rails router, which will send back a 404 response, assuming that you don't have a catch-all route. In your javascript console, you'll get the following error:
146+
147+
> GET http://localhost:3000/1.1-bundle.js
148+
149+
You'll also see the following in your Rails development log:
150+
151+
> Started GET "/1.1-bundle.js" for 127.0.0.1 at 2016-11-29 15:21:55 -0800
152+
>
153+
> ActionController::RoutingError (No route matches [GET] "/1.1-bundle.js")
154+
155+
It's worth mentioning that in Webpack v2, it's possible to register an error handler by calling `catch` on the promise returned by `System.import`, so if you want to do error handling, you should use v2. The [example](#working-example) in `spec/dummy` is currently using Webpack v1.

node_package/src/ComponentRegistry.js

+3-1
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
// key = name used by react_on_rails
2-
// value = { name, component, generatorFunction: boolean }
2+
// value = { name, component, generatorFunction: boolean, isRenderer: boolean }
33
import generatorFunction from './generatorFunction';
44

55
const registeredComponents = new Map();
@@ -20,11 +20,13 @@ export default {
2020
}
2121

2222
const isGeneratorFunction = generatorFunction(component);
23+
const isRenderer = isGeneratorFunction && component.length === 3;
2324

2425
registeredComponents.set(name, {
2526
name,
2627
component,
2728
generatorFunction: isGeneratorFunction,
29+
isRenderer,
2830
});
2931
});
3032
},

node_package/src/ReactOnRails.js

+3-2
Original file line numberDiff line numberDiff line change
@@ -146,7 +146,8 @@ ctx.ReactOnRails = {
146146
* @returns {virtualDomElement} Reference to your component's backing instance
147147
*/
148148
render(name, props, domNodeId) {
149-
const reactElement = createReactElement({ name, props, domNodeId });
149+
const componentObj = ComponentRegistry.get(name);
150+
const reactElement = createReactElement({ componentObj, props, domNodeId });
150151

151152
// eslint-disable-next-line react/no-render-return-value
152153
return ReactDOM.render(reactElement, document.getElementById(domNodeId));
@@ -155,7 +156,7 @@ ctx.ReactOnRails = {
155156
/**
156157
* Get the component that you registered
157158
* @param name
158-
* @returns {name, component, generatorFunction}
159+
* @returns {name, component, generatorFunction, isRenderer}
159160
*/
160161
getComponent(name) {
161162
return ComponentRegistry.get(name);

node_package/src/clientStartup.js

+26-2
Original file line numberDiff line numberDiff line change
@@ -63,11 +63,30 @@ function turbolinksVersion5() {
6363
return (typeof Turbolinks.controller !== 'undefined');
6464
}
6565

66+
function delegateToRenderer(componentObj, props, railsContext, domNodeId, trace) {
67+
const { name, component, isRenderer } = componentObj;
68+
69+
if (isRenderer) {
70+
if (trace) {
71+
console.log(`\
72+
DELEGATING TO RENDERER ${name} for dom node with id: ${domNodeId} with props, railsContext:`,
73+
props, railsContext);
74+
}
75+
76+
component(props, railsContext, domNodeId);
77+
return true;
78+
}
79+
80+
return false;
81+
}
82+
6683
/**
67-
* Used for client rendering by ReactOnRails
84+
* Used for client rendering by ReactOnRails. Either calls ReactDOM.render or delegates
85+
* to a renderer registered by the user.
6886
* @param el
6987
*/
7088
function render(el, railsContext) {
89+
const context = findContext();
7190
const name = el.getAttribute('data-component-name');
7291
const domNodeId = el.getAttribute('data-dom-id');
7392
const props = JSON.parse(el.getAttribute('data-props'));
@@ -76,8 +95,13 @@ function render(el, railsContext) {
7695
try {
7796
const domNode = document.getElementById(domNodeId);
7897
if (domNode) {
98+
const componentObj = context.ReactOnRails.getComponent(name);
99+
if (delegateToRenderer(componentObj, props, railsContext, domNodeId, trace)) {
100+
return;
101+
}
102+
79103
const reactElementOrRouterResult = createReactElement({
80-
name,
104+
componentObj,
81105
props,
82106
domNodeId,
83107
trace,

node_package/src/createReactElement.js

+4-8
Original file line numberDiff line numberDiff line change
@@ -2,26 +2,26 @@
22

33
import React from 'react';
44

5-
import ReactOnRails from './ReactOnRails';
6-
75
/**
86
* Logic to either call the generatorFunction or call React.createElement to get the
97
* React.Component
108
* @param options
11-
* @param options.name
9+
* @param options.componentObj
1210
* @param options.props
1311
* @param options.domNodeId
1412
* @param options.trace
1513
* @param options.location
1614
* @returns {Element}
1715
*/
1816
export default function createReactElement({
19-
name,
17+
componentObj,
2018
props,
2119
railsContext,
2220
domNodeId,
2321
trace,
2422
}) {
23+
const { name, component, generatorFunction } = componentObj;
24+
2525
if (trace) {
2626
if (railsContext && railsContext.serverSide) {
2727
console.log(`RENDERED ${name} to dom node with id: ${domNodeId} with railsContext:`,
@@ -32,10 +32,6 @@ export default function createReactElement({
3232
}
3333
}
3434

35-
const componentObj = ReactOnRails.getComponent(name);
36-
37-
const { component, generatorFunction } = componentObj;
38-
3935
if (generatorFunction) {
4036
return component(props, railsContext);
4137
}

0 commit comments

Comments
 (0)