UNPKG

965 BTypeScriptView Raw
1import * as React from 'react';
2
3type Render = (children: React.ReactNode) => JSX.Element;
4
5type Props = {
6 render: Render;
7 children: React.ReactNode;
8};
9
10const NavigationContent = ({ render, children }: Props) => {
11 return render(children);
12};
13
14export default function useComponent(render: Render) {
15 const renderRef = React.useRef<Render | null>(render);
16
17 // Normally refs shouldn't be mutated in render
18 // But we return a component which will be rendered
19 // So it's just for immediate consumption
20 renderRef.current = render;
21
22 React.useEffect(() => {
23 renderRef.current = null;
24 });
25
26 return React.useRef(({ children }: { children: React.ReactNode }) => {
27 const render = renderRef.current;
28
29 if (render === null) {
30 throw new Error(
31 'The returned component must be rendered in the same render phase as the hook.'
32 );
33 }
34
35 return <NavigationContent render={render}>{children}</NavigationContent>;
36 }).current;
37}