-
-
Save Coridyn/57cb993da4bd19a4892965501c9f0456 to your computer and use it in GitHub Desktop.
Lazy Tippy
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
// Will only render the `content` or `render` elements if the tippy is mounted to the DOM. | |
// Replace <Tippy /> with <LazyTippy /> component and it should work the same. | |
const LazyTippy = forwardRef((props, ref) => { | |
const [mounted, setMounted] = useState(false); | |
const lazyPlugin = { | |
fn: () => ({ | |
onMount: () => setMounted(true), | |
onHidden: () => setMounted(false), | |
}), | |
}; | |
const computedProps = {...props}; | |
computedProps.plugins = [lazyPlugin, ...(props.plugins || [])]; | |
if (props.render) { | |
computedProps.render = (...args) => (mounted ? props.render(...args) : ''); | |
} else { | |
computedProps.content = mounted ? props.content : ''; | |
} | |
return <Tippy {...computedProps} ref={ref} />; | |
}); |
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
// Partially lazy | |
// Will only mount all <Tippy /> content once the singleton itself is mounted. | |
function PartiallyLazySingleton() { | |
const [source, target] = useSingleton(); | |
const [mounted, setMounted] = useState(false); | |
return ( | |
<> | |
<Tippy | |
onShow={() => setMounted(true)} | |
onHidden={() => setMounted(false)} | |
singleton={source} | |
/> | |
<Tippy content={mounted ? <ExpensiveComponent /> : ''} singleton={target}> | |
<button>Hello</button> | |
</Tippy> | |
<Tippy content={mounted ? <ExpensiveComponent /> : ''} singleton={target}> | |
<button>Hello</button> | |
</Tippy> | |
</> | |
); | |
} | |
// Fully lazy | |
// Will only mount the content if that is the currently used singleton content. | |
function LazySingleton() { | |
const [source, target] = useSingleton(); | |
const [mountedRef, setMountedRef] = useState(null); | |
const ref1 = useRef(); | |
const ref2 = useRef(); | |
return ( | |
<> | |
<Tippy | |
onTrigger={(_, event) => setMountedRef(event.currentTarget)} | |
onHidden={() => setMountedRef(null)} | |
singleton={source} | |
/> | |
<Tippy | |
content={mountedRef === ref1.current ? <ExpensiveComponent /> : ''} | |
singleton={target} | |
> | |
<button ref={ref1}>Hello</button> | |
</Tippy> | |
<Tippy | |
content={mountedRef === ref2.current ? <ExpensiveComponent /> : ''} | |
singleton={target} | |
> | |
<button ref={ref2}>Hello</button> | |
</Tippy> | |
</> | |
); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment