Skip to content

Commit 1d08bb3

Browse files
committed
feat: support function provider for portal.root
Allow passing a function to `portal.root` that returns the mount point. Useful when targeting an element managed by a React ref, since refs are not populated when the lightbox first renders.
1 parent 3684860 commit 1d08bb3

3 files changed

Lines changed: 8 additions & 4 deletions

File tree

docs/documentation.md

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -206,14 +206,18 @@ import "yet-another-react-lightbox/styles.css";
206206
<td>portal</td>
207207
<td>
208208
&#123;<br />
209-
&nbsp;&nbsp;root?: DocumentFragment | Element | null;<br />
209+
&nbsp;&nbsp;root?: (() =&gt; DocumentFragment | Element | null) | DocumentFragment | Element | null;<br />
210210
&nbsp;&nbsp;container?: React.HTMLAttributes&lt;HTMLDivElement&gt;;<br />
211211
&#125;
212212
</td>
213213
<td>
214214
<p>Portal settings.</p>
215215
<ul>
216-
<li>`root` - custom portal mount point. By default, the portal is mounted as a child of the document body.</li>
216+
<li>
217+
`root` - custom portal mount point. By default, the portal is mounted as a child of the document body.
218+
Can also be a function that returns the mount point - useful when targeting an element managed by a React
219+
ref (e.g. `root: () => portalRootRef.current`).
220+
</li>
217221
<li>`container` - HTML attributes for the portal container element (e.g., `{ dir: "rtl" }`).</li>
218222
</ul>
219223
</td>

src/modules/Portal.tsx

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -149,7 +149,7 @@ export function Portal({
149149
>
150150
{children}
151151
</LightboxRoot>,
152-
root || document.body,
152+
(typeof root === "function" ? root() : root) || document.body,
153153
)
154154
: null;
155155
}

src/types.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -255,7 +255,7 @@ export interface ControllerRef {
255255
/** Portal settings */
256256
export interface PortalSettings {
257257
/** portal mount point */
258-
root?: DocumentFragment | Element | null;
258+
root?: (() => DocumentFragment | Element | null) | DocumentFragment | Element | null;
259259
/** HTML attributes for the portal container */
260260
container?: React.HTMLAttributes<HTMLDivElement>;
261261
}

0 commit comments

Comments
 (0)