Skip to content

Commit

Permalink
[React] Fix window types
Browse files Browse the repository at this point in the history
  • Loading branch information
AlexandreGerault authored and weaverryan committed Nov 21, 2022
1 parent 843f1dd commit 9b43394
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 3 deletions.
16 changes: 14 additions & 2 deletions src/React/Resources/assets/src/register_controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,8 +9,20 @@

'use strict';

import { ComponentClass, FunctionComponent } from 'react';

type Component = string | FunctionComponent<object> | ComponentClass<object, any>;

declare global {
function resolveReactComponent(name: string): Component;

interface Window {
resolveReactComponent(name: string): Component;
}
}

export function registerReactControllerComponents(context: __WebpackModuleApi.RequireContext) {
const reactControllers: { [key: string]: object } = {};
const reactControllers: { [key: string]: Component } = {};

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

// Expose a global React loader to allow rendering from the Stimulus controller
(window as any).resolveReactComponent = (name: string): object => {
window.resolveReactComponent = (name: string): Component => {
const component = reactControllers[`./${name}.jsx`] || reactControllers[`./${name}.tsx`];
if (typeof component === 'undefined') {
throw new Error('React controller "' + name + '" does not exist');
Expand Down
6 changes: 5 additions & 1 deletion src/React/Resources/assets/src/render_controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ import { createRoot } from 'react-dom/client';
import { Controller } from '@hotwired/stimulus';

export default class extends Controller {
readonly componentValue: string;
readonly componentValue?: string;
readonly propsValue?: object;

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

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

if (!this.componentValue) {
throw new Error('No component specified.');
}

const component = window.resolveReactComponent(this.componentValue);
this._renderReactElement(React.createElement(component, props, null));

Expand Down

0 comments on commit 9b43394

Please sign in to comment.