@@ -2,6 +2,26 @@ import * as React from 'react';
22import type { CreateParams , ReactComponent , RenderFunction , CreateReactOutputResult } from './types/index' ;
33import { isServerRenderHash , isPromise } from './isServerRenderResult' ;
44
5+ function createReactElementFromRenderFunctionResult (
6+ renderFunctionResult : ReactComponent ,
7+ name : string ,
8+ props : Record < string , unknown > | undefined ,
9+ ) : React . ReactElement {
10+ if ( React . isValidElement ( renderFunctionResult ) ) {
11+ // If already a ReactElement, then just return it.
12+ console . error (
13+ `Warning: ReactOnRails: Your registered render-function (ReactOnRails.register) for ${ name }
14+ incorrectly returned a React Element (JSX). Instead, return a React Function Component by
15+ wrapping your JSX in a function. ReactOnRails v13 will throw error on this, as React Hooks do not
16+ work if you return JSX. Update by wrapping the result JSX of ${ name } in a fat arrow function.` ,
17+ ) ;
18+ return renderFunctionResult ;
19+ }
20+
21+ // If a component, then wrap in an element
22+ return React . createElement ( renderFunctionResult , props ) ;
23+ }
24+
525/**
626 * Logic to either call the renderFunction or call React.createElement to get the
727 * React.Component
@@ -60,24 +80,15 @@ export default function createReactOutput({
6080 if ( typeof result === 'string' ) {
6181 return result ;
6282 }
83+ // If the result is a function, then it returned a React Component (even class components are functions).
84+ if ( typeof result === 'function' ) {
85+ return createReactElementFromRenderFunctionResult ( result , name , props ) ;
86+ }
6387 return JSON . stringify ( result ) ;
6488 } ) ;
6589 }
6690
67- if ( React . isValidElement ( renderFunctionResult ) ) {
68- // If already a ReactElement, then just return it.
69- console . error (
70- `Warning: ReactOnRails: Your registered render-function (ReactOnRails.register) for ${ name }
71- incorrectly returned a React Element (JSX). Instead, return a React Function Component by
72- wrapping your JSX in a function. ReactOnRails v13 will throw error on this, as React Hooks do not
73- work if you return JSX. Update by wrapping the result JSX of ${ name } in a fat arrow function.` ,
74- ) ;
75- return renderFunctionResult ;
76- }
77-
78- // If a component, then wrap in an element
79- const reactComponent = renderFunctionResult ;
80- return React . createElement ( reactComponent , props ) ;
91+ return createReactElementFromRenderFunctionResult ( renderFunctionResult , name , props ) ;
8192 }
8293 // else
8394 return React . createElement ( component as ReactComponent , props ) ;
0 commit comments