import { i18n } from '@osd/i18n' ; import React , { useRef , useEffect , useState , Component } from 'react' ; import ReactDOM from 'react-dom' ; import { MountPoint } from 'opensearch-dashboards/public' ; import { useIfMounted } from './utils' ; interface MountPointPortalProps { setMountPoint : ( mountPoint : MountPoint < HTMLElement > ) => void ; } /**
 * Utility component to portal a part of a react application into the provided `MountPoint`.
 */ export const MountPointPortal = ( { children , setMountPoint } ) => { const [ shouldRender , setShouldRender ] = useState ( false ) ; const el = useRef < HTMLElement > ( ) ; const ifMounted = useIfMounted ( ) ; useEffect ( ( ) => { setMountPoint ( ( element ) => { ifMounted ( ( ) => { el . current = element ; setShouldRender ( true ) ; } ) ; return ( ) => { ifMounted ( ( ) => { setShouldRender ( false ) ; el . current = undefined ; } ) ; } ; } ) ; return ( ) => { ifMounted ( ( ) => { setShouldRender ( false ) ; el . current = undefined ; } ) ; } ; } , [ setMountPoint ] ) ; if ( shouldRender && el . current ) { return ReactDOM . createPortal ( < MountPointPortalErrorBoundary > { children } < /MountPointPortalErrorBoundary>, el.current); } else { return null ; } } ; class MountPointPortalErrorBoundary extends Component < { } , { error ? : any ; } > { state = { error : undefined , } ; static getDerivedStateFromError ( error ) { return { error } ; } componentDidCatch ( ) { } render ( ) { if ( this . state . error ) { return ( < p > { i18n . translate ( 'opensearch-dashboards-react.mountPointPortal.errorMessage' , { defaultMessage : 'Error rendering portal content' , } ) } < /p>); } return this . props . children ; } }