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.
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.
The hook created by us can be used in the following way:
Check implementation below to understand the power of encapsulation.
- 1. Rendering
Creating portals with custom usePortal hook
We will change the screens with useStepper hook
Manage components appearance with useToggle hook
Removing server warnings for useLayoutEffect with custom hook
First interaction detection with useOnInteraction hook
- 2. Forms
- 3. Events
Read the scroll metadata and direction with useScroll hook
Using clipboard with useClipboard hook
Detect outside click with the useClickOutside hook
Deep dive into useIntersectionObserver hook
Element size measurement with useElementSize hook
- 4. Guards
- 5. Interactions