Skip to content

Commit 9b43394

Browse files
AlexandreGeraultweaverryan
authored andcommitted
[React] Fix window types
1 parent 843f1dd commit 9b43394

File tree

2 files changed

+19
-3
lines changed

2 files changed

+19
-3
lines changed

src/React/Resources/assets/src/register_controller.ts

Lines changed: 14 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -9,8 +9,20 @@
99

1010
'use strict';
1111

12+
import { ComponentClass, FunctionComponent } from 'react';
13+
14+
type Component = string | FunctionComponent<object> | ComponentClass<object, any>;
15+
16+
declare global {
17+
function resolveReactComponent(name: string): Component;
18+
19+
interface Window {
20+
resolveReactComponent(name: string): Component;
21+
}
22+
}
23+
1224
export function registerReactControllerComponents(context: __WebpackModuleApi.RequireContext) {
13-
const reactControllers: { [key: string]: object } = {};
25+
const reactControllers: { [key: string]: Component } = {};
1426

1527
const importAllReactComponents = (r: __WebpackModuleApi.RequireContext) => {
1628
r.keys().forEach((key) => (reactControllers[key] = r(key).default));
@@ -19,7 +31,7 @@ export function registerReactControllerComponents(context: __WebpackModuleApi.Re
1931
importAllReactComponents(context);
2032

2133
// Expose a global React loader to allow rendering from the Stimulus controller
22-
(window as any).resolveReactComponent = (name: string): object => {
34+
window.resolveReactComponent = (name: string): Component => {
2335
const component = reactControllers[`./${name}.jsx`] || reactControllers[`./${name}.tsx`];
2436
if (typeof component === 'undefined') {
2537
throw new Error('React controller "' + name + '" does not exist');

src/React/Resources/assets/src/render_controller.ts

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,7 @@ import { createRoot } from 'react-dom/client';
1414
import { Controller } from '@hotwired/stimulus';
1515

1616
export default class extends Controller {
17-
readonly componentValue: string;
17+
readonly componentValue?: string;
1818
readonly propsValue?: object;
1919

2020
static values = {
@@ -27,6 +27,10 @@ export default class extends Controller {
2727

2828
this._dispatchEvent('react:connect', { component: this.componentValue, props: props });
2929

30+
if (!this.componentValue) {
31+
throw new Error('No component specified.');
32+
}
33+
3034
const component = window.resolveReactComponent(this.componentValue);
3135
this._renderReactElement(React.createElement(component, props, null));
3236

0 commit comments

Comments
 (0)