Last active
November 13, 2019 14:20
-
-
Save Akiyamka/5269d67f8a5a3796debc436703195417 to your computer and use it in GitHub Desktop.
React portal in real life
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import React, { useRef } from 'react'; | |
import ReactDOM from 'react-dom'; | |
const Portal = { | |
open(ref) { | |
this.ref = ref; | |
}, | |
close() { | |
this.ref = null; | |
}, | |
component({ children }) { | |
return this.ref ? ReactDOM.createPortal( | |
children, | |
this.ref | |
) : null; | |
} | |
}; | |
export default function Tooltips() { | |
const tooltipRef = useRef(); | |
tooltipRef.current && Portal.open(tooltipRef.current); | |
return <div ref={tooltipRef}> | |
{/* Some layout */} | |
</div> | |
} | |
export function PortalToTooltips(props) { | |
return Portal.component(props); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment