• Что бы вступить в ряды "Принятый кодер" Вам нужно:
    Написать 10 полезных сообщений или тем и Получить 10 симпатий.
    Для того кто не хочет терять время,может пожертвовать средства для поддержки сервеса, и вступить в ряды VIP на месяц, дополнительная информация в лс.

  • Пользаватели которые будут спамить, уходят в бан без предупреждения. Спам сообщения определяется администрацией и модератором.

  • Гость, Что бы Вы хотели увидеть на нашем Форуме? Изложить свои идеи и пожелания по улучшению форума Вы можете поделиться с нами здесь. ----> Перейдите сюда
  • Все пользователи не прошедшие проверку электронной почты будут заблокированы. Все вопросы с разблокировкой обращайтесь по адресу электронной почте : info@guardianelinks.com . Не пришло сообщение о проверке или о сбросе также сообщите нам.

From Root to Anywhere: How React Portals Work

Lomanu4 Оффлайн

Lomanu4

Команда форума
Администратор
Регистрация
1 Мар 2015
Сообщения
1,481
Баллы
155
Introduction
React normally renders components into a specific DOM hierarchy. But what if you need to render something outside of that? That’s where React Portals come in.
In this post, we’ll look at what a Portal is when to use it, and how to implement one.
What Is a React Portal?
i.React Portals provide a way to render child components outside of their parent's DOM hierarchy. This functionality is useful in scenarios where a component needs to visually "break out" of its container, such as with modals, tooltips, or pop-up menus.

ii.The ReactDOM.createPortal method is used to achieve this, taking two arguments: the child element to be rendered and the DOM node where it should be rendered.

syntax-ReactDOM.createProtal(children,container)

For Example:
Let’s say we want a modal to appear above all content, even if it's deeply nested in the React tree.
HTML Structure


<body>
<div id="root"></div>
<div id="modal"></div>
</body>

React Component


import ReactDOM from "react-dom"
import { X } from 'lucide-react'; // this is for close icon ,it is not
belongs to react portals concept

const Modal=({children})=>{

return ReactDOM.createPortal(
<div className=" fixed bottom-0 top-0 overflow-hidden left-0 right-0 bg-[#00000086] flex justify-center items-center z-50 ">
<div className="bg-white relative rounded-[10px] px-3 max-lg:absolute max-lg:bottom-0 min-w-[300px] lg:max-w-[600px] overflow-auto max-lg:w-full pt-4 min-h-[300px] max-lg:h-[90vh] lg:max-h-[400px]">
<button className="absolute right-2 top-2 max-lg:hidden inline"><X/></button>
{children}

</div>
</div>,
document.getElementById("modal")

)
}

export default Modal

How to use It


<Modal>
<h3>This is modal Content</h3>
</Modal>

When to use It?
React Portals used in below scenario

  • Modals and Dialogs
  • Notification Bar
  • Tooltips and dropdowns

Conclusion
This is particularly valuable for creating elements like modals, tooltips, notifications, or dropdowns that need to visually break out of their container's boundaries to avoid styling conflicts, layout issues overflow-hidden or z-index problems.


Пожалуйста Авторизируйтесь или Зарегистрируйтесь для просмотра скрытого текста.

 
Вверх Снизу