| 1 |
import React, { createContext, useContext } from 'react' |
| 2 |
import { createRoot } from 'react-dom/client' |
| 3 |
import type { Context, FunctionComponent } from 'react' |
| 4 |
|
| 5 |
export const loadComponent = (containerId: string, Component: FunctionComponent): void => { |
| 6 |
const container = document.getElementById(containerId) |
| 7 |
|
| 8 |
if (container) { |
| 9 |
const root = createRoot(container) |
| 10 |
root.render(<Component />) |
| 11 |
} else { |
| 12 |
console.error(`Could not find element #${containerId}.`) |
| 13 |
} |
| 14 |
} |
| 15 |
|
| 16 |
export const createContextHook = <T, >(hookName: string): [ |
| 17 |
Context<T | undefined>, |
| 18 |
() => T |
| 19 |
] => { |
| 20 |
const Context = createContext<T | undefined>(undefined) |
| 21 |
|
| 22 |
const useContextHook = (): T => { |
| 23 |
const value = useContext(Context) |
| 24 |
|
| 25 |
if (value === undefined) { |
| 26 |
throw Error(`${hookName} can only be used within a corresponding context provider.`) |
| 27 |
} |
| 28 |
|
| 29 |
return value |
| 30 |
} |
| 31 |
|
| 32 |
return [Context, useContextHook] |
| 33 |
} |
| 34 |
|