1010'use strict' ;
1111
1212import React , { ReactElement } from 'react' ;
13+ import { createRoot } from 'react-dom/client' ;
1314import { Controller } from '@hotwired/stimulus' ;
1415
1516export default class extends Controller {
@@ -24,52 +25,26 @@ export default class extends Controller {
2425 connect ( ) {
2526 this . _dispatchEvent ( 'react:connect' , { component : this . componentValue , props : this . propsValue } ) ;
2627
27- // Use a timeout to avoid mounting and demounting right after
28- if ( ( this . element as any ) . timeout ) {
29- clearTimeout ( ( this . element as any ) . timeout ) ;
30- }
28+ const component = window . resolveReactComponent ( this . componentValue ) ;
29+ this . _renderReactElement ( React . createElement ( component , this . propsValue , null ) ) ;
3130
32- ( this . element as any ) . timeout = setTimeout ( ( ) => {
33- const component = window . resolveReactComponent ( this . componentValue ) ;
34- this . _renderReactElement ( React . createElement ( component , this . propsValue , null ) ) ;
35-
36- this . _dispatchEvent ( 'react:mount' , {
37- componentName : this . componentValue ,
38- component : component ,
39- props : this . propsValue ,
40- } ) ;
41- } , 50 ) ;
31+ this . _dispatchEvent ( 'react:mount' , {
32+ componentName : this . componentValue ,
33+ component : component ,
34+ props : this . propsValue ,
35+ } ) ;
4236 }
4337
4438 disconnect ( ) {
45- ( this . element as any ) . unmount ( ) ;
39+ ( this . element as any ) . root . unmount ( ) ;
4640 this . _dispatchEvent ( 'react:unmount' , { component : this . componentValue , props : this . propsValue } ) ;
4741 }
4842
4943 _renderReactElement ( reactElement : ReactElement ) {
50- if ( parseInt ( React . version ) >= 18 ) {
51- // React 18+ rendering
52- // eslint-disable-next-line @typescript-eslint/no-var-requires
53- const root = require ( 'react-dom/client' ) . createRoot ( this . element ) ;
54- root . render ( reactElement ) ;
55-
56- // Register a way to unmount this element
57- ( this . element as any ) . unmount = ( ) => {
58- root . unmount ( ) ;
59- } ;
60-
61- return ;
62- }
63-
64- // Up to React 17 rendering
65- // eslint-disable-next-line @typescript-eslint/no-var-requires
66- const reactDom = require ( 'react-dom' ) ;
67- reactDom . render ( reactElement , this . element ) ;
44+ const root = createRoot ( this . element ) ;
45+ root . render ( reactElement ) ;
6846
69- // Register a way to unmount this element
70- ( this . element as any ) . unmount = ( ) => {
71- reactDom . unmountComponentAtNode ( this . element ) ;
72- } ;
47+ ( this . element as any ) . root = root ;
7348 }
7449
7550 _dispatchEvent ( name : string , payload : any ) {
0 commit comments