diff --git a/.storybook/main.ts b/.storybook/main.ts index 57050f3dd..b023e42c7 100644 --- a/.storybook/main.ts +++ b/.storybook/main.ts @@ -39,7 +39,8 @@ const config: StorybookConfig = { './SearchCore': require.resolve('../tests/__fixtures__/core/SearchCore.ts'), '../utils/location-operations': require.resolve('../tests/__fixtures__/utils/location-operations.ts') }, - } + }, + externals: ["react-dom/client"] }), env: (config) => { diff --git a/src/components/MapboxMap.tsx b/src/components/MapboxMap.tsx index 48b12b80c..99be744f0 100644 --- a/src/components/MapboxMap.tsx +++ b/src/components/MapboxMap.tsx @@ -2,7 +2,7 @@ import React, { useRef, useEffect } from 'react'; import mapboxgl from 'mapbox-gl'; import { Result, useSearchState } from '@yext/search-headless-react'; import { useDebouncedFunction } from '../hooks/useDebouncedFunction'; -import ReactDOM from 'react-dom'; +import { renderReact } from './utils/renderReact'; /** * A functional component that can be used to render a custom marker on the map. @@ -136,13 +136,11 @@ export function MapboxMap({ const el = document.createElement('div'); const markerOptions: mapboxgl.MarkerOptions = {}; if (PinComponent) { - renderPinComponentByReactVersion( - el, - i, - mapbox, - result, - PinComponent - ); + renderReact(, el); markerOptions.element = el; } const marker = new mapboxgl.Marker(markerOptions) @@ -186,31 +184,3 @@ function getDefaultCoordinate(result: Result): Coordinate | undefined { } return yextDisplayCoordinate; } - -function renderPinComponentByReactVersion( - el: HTMLDivElement | null, - i: number, - mapbox: mapboxgl.Map, - result: Result, - PinComponent: PinComponent -) { - - if (React.version.startsWith('18')) { - import('react-dom/client').then(({ createRoot }) => { - const root = createRoot(el!); - root.render( - - ); - }); - }else{ - ReactDOM.render(, el) - } -} \ No newline at end of file diff --git a/src/components/utils/renderReact.ts b/src/components/utils/renderReact.ts new file mode 100644 index 000000000..70f58887d --- /dev/null +++ b/src/components/utils/renderReact.ts @@ -0,0 +1,17 @@ +import React from 'react'; +import ReactDOM from 'react-dom'; + +export function renderReact(children: JSX.Element, container: Element) { + try { + if (!React.version.startsWith('18')) { + throw new Error('Using React <18. Skip createRoot rendering.'); + } + // @ts-ignore + import('react-dom/client').then(({ createRoot }) => { + const root = createRoot(container); + root.render(children); + }); + } catch { + ReactDOM.render(children, container); + } +} diff --git a/tsconfig.json b/tsconfig.json index e0400421c..b24ea57b6 100644 --- a/tsconfig.json +++ b/tsconfig.json @@ -10,8 +10,8 @@ "declarationMap": true, "sourceMap": true, "jsx": "react", - "target": "esnext", - "module": "esnext", + "target": "es2022", + "module": "es2022" }, "include": [ "src"