-
-
Notifications
You must be signed in to change notification settings - Fork 70
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
refactor(usePortal): use
createPortal
directly (#368)
- Loading branch information
Showing
1 changed file
with
10 additions
and
43 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,47 +1,14 @@ | ||
import React, { useState, useEffect, ReactPortal, useRef } from 'react'; | ||
import { PropsWithChildren, useCallback, useState } from 'react'; | ||
import { createPortal } from 'react-dom'; | ||
import { createRoot, Root } from 'react-dom/client'; | ||
|
||
interface State { | ||
render: (props: { children: React.ReactNode }) => ReactPortal | null; | ||
remove: (elm?: HTMLElement) => void; | ||
} | ||
|
||
export const usePortal = () => { | ||
const ref = useRef<Root>(); | ||
const [container] = React.useState<HTMLDivElement>(() => { | ||
const el = document.createElement('div'); | ||
ref.current = createRoot(el); | ||
return el; | ||
}); | ||
const [portal, setPortal] = useState<State>({ | ||
render: () => null, | ||
remove: () => null, | ||
}); | ||
|
||
const ReactCreatePortal = React.useCallback<(elmm: HTMLDivElement) => State>((elmm) => { | ||
const Portal: State['render'] = ({ children }) => { | ||
if (!children) return null; | ||
return createPortal(children, elmm); | ||
}; | ||
const remove: State['remove'] = (elm) => { | ||
// https://stackoverflow.com/a/74445760/1334703 | ||
const timeout = setTimeout(() => { | ||
elm && ref.current?.unmount(); | ||
clearTimeout(timeout); | ||
}); | ||
}; | ||
return { render: Portal, remove }; | ||
}, []); | ||
|
||
useEffect(() => { | ||
if (container) portal.remove(); | ||
const newPortal = ReactCreatePortal(container); | ||
setPortal(newPortal); | ||
return () => { | ||
newPortal.remove(container); | ||
}; | ||
}, [container]); | ||
|
||
return { Portal: portal.render, container }; | ||
const [container] = useState<HTMLDivElement>(() => document.createElement('div')); | ||
const Portal = useCallback( | ||
function Portal({ children }: PropsWithChildren) { | ||
return createPortal(children, container); | ||
}, | ||
[container], | ||
); | ||
|
||
return { Portal, container }; | ||
}; |