Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

React 18 conditional support #1449

Closed
wants to merge 4 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 10 additions & 7 deletions node_package/src/ReactOnRails.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,10 +16,10 @@ import type {
ErrorOptions,
ReactComponentOrRenderFunction,
AuthenticityHeaders,
StoreGenerator
StoreGenerator,
RootHydrateFunction
} from './types/index';
import reactHydrate from './reactHydrate';
import reactRender from './reactRender';
import renderHelperPromise from './helpers/renderHelper';

/* eslint-disable @typescript-eslint/no-explicit-any */
type Store = any;
Expand Down Expand Up @@ -184,13 +184,16 @@ ctx.ReactOnRails = {
* @param hydrate Pass truthy to update server rendered html. Default is falsy
* @returns {virtualDomElement} Reference to your component's backing instance
*/
render(name: string, props: Record<string, string>, domNodeId: string, hydrate: boolean): void | Element | Component {
render(name: string, props: Record<string, string>, domNodeId: string, hydrate: boolean): Promise<void | Element | Component> {
const componentObj = ComponentRegistry.get(name);
const reactElement = createReactOutput({ componentObj, props, domNodeId });

const render = hydrate ? reactHydrate : reactRender;
// eslint-disable-next-line react/no-render-return-value
return render(document.getElementById(domNodeId) as Element, reactElement as ReactElement);
let rendered: ReturnType<RootHydrateFunction>

return renderHelperPromise.then(({ reactHydrate, reactRender }) => {
const render = hydrate ? reactHydrate : reactRender;
return render(document.getElementById(domNodeId) as Element, reactElement as ReactElement);
})
},

/**
Expand Down
92 changes: 52 additions & 40 deletions node_package/src/clientStartup.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,8 +9,7 @@ import type {

import createReactOutput from './createReactOutput';
import {isServerRenderHash} from './isServerRenderResult';
import reactHydrate from './reactHydrate';
import reactRender from './reactRender';
import renderHelperPromise from './helpers/renderHelper';

declare global {
interface Window {
Expand Down Expand Up @@ -138,47 +137,59 @@ function domNodeIdForEl(el: Element): string {
function render(el: Element, railsContext: RailsContext): void {
const context = findContext();
// This must match lib/react_on_rails/helper.rb
const name = el.getAttribute('data-component-name') || "";
const name = el.getAttribute('data-component-name') || '';
const domNodeId = domNodeIdForEl(el);
const props = (el.textContent !== null) ? JSON.parse(el.textContent) : {};
const trace = el.getAttribute('data-trace') === "true";

try {
const domNode = document.getElementById(domNodeId);
if (domNode) {
const componentObj = context.ReactOnRails.getComponent(name);
if (delegateToRenderer(componentObj, props, railsContext, domNodeId, trace)) {
return;
}

// Hydrate if available and was server rendered
// @ts-expect-error potentially present if React 18 or greater
const shouldHydrate = !!(ReactDOM.hydrate || ReactDOM.hydrateRoot) && !!domNode.innerHTML;

const reactElementOrRouterResult = createReactOutput({
componentObj,
props,
domNodeId,
trace,
railsContext,
shouldHydrate,
});

if (isServerRenderHash(reactElementOrRouterResult)) {
throw new Error(`\
You returned a server side type of react-router error: ${JSON.stringify(reactElementOrRouterResult)}
const props = el.textContent !== null ? JSON.parse(el.textContent) : {};
const trace = el.getAttribute('data-trace') === 'true';

renderHelperPromise.then(({ canHydrate, reactHydrate, reactRender }) => {
try {
const domNode = document.getElementById(domNodeId);
if (domNode) {
const componentObj = context.ReactOnRails.getComponent(name);
if (
delegateToRenderer(
componentObj,
props,
railsContext,
domNodeId,
trace
)
) {
return;
}

// Hydrate if available and was server rendered
const shouldHydrate = canHydrate && !!domNode.innerHTML;

const reactElementOrRouterResult = createReactOutput({
componentObj,
props,
domNodeId,
trace,
railsContext,
shouldHydrate,
});

if (isServerRenderHash(reactElementOrRouterResult)) {
throw new Error(`\
You returned a server side type of react-router error: ${JSON.stringify(
reactElementOrRouterResult
)}
You should return a React.Component always for the client side entry point.`);
} else if (shouldHydrate) {
reactHydrate(domNode, reactElementOrRouterResult as ReactElement);
} else {
reactRender(domNode, reactElementOrRouterResult as ReactElement);
} else if (shouldHydrate) {
reactHydrate(domNode, reactElementOrRouterResult as ReactElement);
} else {
reactRender(domNode, reactElementOrRouterResult as ReactElement);
}
}
} catch (e: any) {
e.message =
`ReactOnRails encountered an error while rendering component: ${name}.\n` +
`Original message: ${e.message}`;
throw e;
}
} catch (e) {
e.message = `ReactOnRails encountered an error while rendering component: ${name}.\n` +
`Original message: ${e.message}`;
throw e;
}
});
}

function parseRailsContext(): RailsContext | null {
Expand Down Expand Up @@ -213,8 +224,9 @@ function unmount(el: Element): void {
const domNode = document.getElementById(domNodeId);
if(domNode === null){return;}
try {
// Might need updating? https://reactjs.org/blog/2022/03/08/react-18-upgrade-guide.html
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

unmountComponentAtNode is considered legacy https://reactjs.org/docs/react-dom.html#unmountcomponentatnode but would need to store references to root instead if we were to update

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Please see #1466.

ReactDOM.unmountComponentAtNode(domNode);
} catch (e) {
} catch (e: any) {
console.info(`Caught error calling unmountComponentAtNode: ${e.message} for domNode`,
domNode, e);
}
Expand Down
9 changes: 9 additions & 0 deletions node_package/src/helpers/legacyRootHandler.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
// import ReactDOM from 'react-dom';
// import type { RootRenderFunction, RootHydrateFunction } from '../types';

// export const canHydrate = !!ReactDOM.hydrate

// export const hydrate: RootHydrateFunction = (domNode, reactElement) => ReactDOM.hydrate(reactElement, domNode)

// // eslint-disable-next-line react/no-render-return-value
// export const render: RootRenderFunction = (domNode, reactElement) => ReactDOM.render(reactElement, domNode)
14 changes: 14 additions & 0 deletions node_package/src/helpers/modernRootHandler.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
// // @ts-expect-error react-dom/client only available in React 18
// // eslint-disable-next-line import/no-unresolved
// import ReactDOM from 'react-dom/client';
// import type { RootRenderFunction, RootHydrateFunction } from '../types';

// export const canHydrate = !!ReactDOM.hydrateRoot;

// export const hydrate: RootHydrateFunction = (domNode, reactElement) => ReactDOM.hydrateRoot(domNode, reactElement);

// export const render: RootRenderFunction = (domNode, reactElement) => {
// const root = ReactDOM.createRoot(domNode);
// root.render(reactElement);
// return root;
// };
38 changes: 38 additions & 0 deletions node_package/src/helpers/renderHelper.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
import supportsReactCreateRoot from './supportsReactCreateRoot';
import type { RootRenderFunction, RootHydrateFunction } from '../types';

interface RenderHelper {
canHydrate: boolean;
reactHydrate: RootHydrateFunction;
reactRender: RootRenderFunction;
}

export default (async (): Promise<RenderHelper> => {
const toImport = supportsReactCreateRoot === true ? 'react-dom/client' : 'react-dom';
const ReactDOM = await import(toImport);

let canHydrate: RenderHelper['canHydrate'];
let reactHydrate: RenderHelper['reactHydrate'];
let reactRender: RenderHelper['reactRender'];

if (supportsReactCreateRoot === true) {
canHydrate = !!ReactDOM.hydrateRoot;
reactHydrate = (domNode, reactElement) => ReactDOM.hydrateRoot(domNode, reactElement);
reactRender = (domNode, reactElement) => {
const root = ReactDOM.createRoot(domNode);
root.render(reactElement);
return root;
};
} else {
canHydrate = !!ReactDOM.hydrate;
reactHydrate = (domNode, reactElement) => ReactDOM.hydrate(reactElement, domNode);
// eslint-disable-next-line react/no-render-return-value
reactRender = (domNode, reactElement) => ReactDOM.render(reactElement, domNode);
}

return {
canHydrate,
reactHydrate,
reactRender,
};
})();
12 changes: 0 additions & 12 deletions node_package/src/reactHydrate.ts

This file was deleted.

15 changes: 0 additions & 15 deletions node_package/src/reactRender.ts

This file was deleted.

6 changes: 6 additions & 0 deletions node_package/src/types/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,10 @@ interface RenderFunction {

type ReactComponentOrRenderFunction = ReactComponent | RenderFunction;

type RootRenderFunction = (domNode: Element, reactElement: ReactElement) => void | Element | Component;

type RootHydrateFunction = RootRenderFunction;

export type { // eslint-disable-line import/prefer-default-export
ReactComponentOrRenderFunction,
ReactComponent,
Expand All @@ -61,6 +65,8 @@ export type { // eslint-disable-line import/prefer-default-export
StoreGenerator,
CreateReactOutputResult,
ServerRenderResult,
RootRenderFunction,
RootHydrateFunction,
}

export interface RegisteredComponent {
Expand Down
2 changes: 1 addition & 1 deletion node_package/tests/supportsReactCreateRoot.test.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import ReactDOM from 'react-dom';
import { isVersionGreaterThanOrEqualTo18 } from '../src/supportsReactCreateRoot';
import { isVersionGreaterThanOrEqualTo18 } from '../src/helpers/supportsReactCreateRoot';

describe('supportsReactCreateRoot', () => {
it('returns false for ReactDOM v16, no version', () => {
Expand Down