Skip to content

Commit

Permalink
fix: require react dom #3704 (#3818)
Browse files Browse the repository at this point in the history
* fix: require react dom #3704

* test: ignore load create portal function istanbul
  • Loading branch information
gwsbhqt authored May 13, 2023
1 parent 30db04a commit c3d028d
Showing 1 changed file with 31 additions and 11 deletions.
42 changes: 31 additions & 11 deletions packages/react/src/shared/render.ts
Original file line number Diff line number Diff line change
@@ -1,21 +1,41 @@
import React from 'react'
import React, { type ReactNode, type ReactPortal } from 'react'
import { globalThisPolyfill } from '@formily/shared'

const env = {
portalDOM: null,
ReactDOM: null,
interface Env {
portalDOM?: HTMLDivElement
createPortal?: (children: ReactNode, container: Element) => ReactPortal
}

const env: Env = {
portalDOM: globalThisPolyfill?.document?.createElement?.('div'),
createPortal: globalThisPolyfill?.['ReactDOM']?.createPortal,
}

/* istanbul ignore next */
const loadCreatePortal = () => {
if (!env.createPortal) {
try {
// eslint-disable-next-line @typescript-eslint/no-var-requires
env.createPortal ??= require('react-dom')?.createPortal
} catch {}
}
if (!env.createPortal) {
try {
// @ts-ignore
import('react-dom')
.then((module) => (env.createPortal ??= module?.createPortal))
.catch()
} catch {}
}
}

export const render = (element: React.ReactElement) => {
if (globalThisPolyfill.navigator?.product === 'ReactNative') return null
if (globalThisPolyfill.document) {
env.portalDOM =
env.portalDOM || globalThisPolyfill['document'].createElement('div')
env.ReactDOM =
env.ReactDOM || globalThisPolyfill['ReactDOM'] || require('react-dom')
//eslint-disable-next-line
return env.ReactDOM.createPortal(element, env.portalDOM)
if (env.portalDOM && env.createPortal) {
return env.createPortal(element, env.portalDOM)
} else {
return React.createElement('template', {}, element)
}
}

loadCreatePortal()

0 comments on commit c3d028d

Please sign in to comment.