Intro
We'll use native React portal API to move any component outside of the root div. Later, we'll wrap it with a custom hook to avoid z-index problems.
Why?
Sometimes you want to render components outside div with id="root". It may happen when you're working on some components that use z-index or absolute/fixed/static positions in css - these could be modals, alerts or prompts.
This can be achieved by usage of React.createPortal(). Remember don't repeat yourself. Don't use this API everywhere and stop copying the logic all the time. It's a good idea to create a hook for that.
Usage
The hook created by us can be used in the following way:
Loading
Implementation
Check implementation below to understand the power of encapsulation.
Loading
- 1. Rendering
16 minutes
Creating portals with custom usePortal hook
2 m
We will change the screens with useStepper hook
3 m
Manage components appearance with useToggle hook
4 m
Removing server warnings for useLayoutEffect with custom hook
3 m
First interaction detection with useOnInteraction hook
4 m
- 2. Forms
4 minutes
- 3. Events
26 minutes
Read the scroll metadata and direction with useScroll hook
5 m
Using clipboard with useClipboard hook
4 m
Detect outside click with the useClickOutside hook
6 m
Deep dive into useIntersectionObserver hook
4 m
Element size measurement with useElementSize hook
7 m
- 4. Guards
5 minutes
- 5. Interactions
5 minutes
Comments
Add your honest opinion about this article and help us improve the content.