Article thumbnail

🔰 Creating portals with custom usePortal hook

2m
frontend
ui
hooks

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

I create content regularly!

I hope you found my post interesting. If so, maybe you'll take a peek at my LinkedIn, where I publish posts daily.

Comments

Add your honest opinion about this article and help us improve the content.

created: 20-03-2023
updated: 20-03-2023