Packages

React inside Phoenix LiveView — async code splitting, client-side props diffing, and zero-config component discovery.

Retired package: Release invalid - Not production-ready

Current section

Files

Jump to
react_phx assets utils.ts
Raw

assets/utils.ts

import { createElement, type ComponentType, type ReactNode } from "react";
import { ReactPhxProvider } from "./context";
import { ReactPhxErrorBoundary } from "./errorBoundary";
import type { HookProps, LiveViewHook } from "./types";
/**
* Extract the six hook functions from a LiveView hook instance and bind them
* so they can be passed as props to React components.
*/
export function getHookFunctions(hook: LiveViewHook): HookProps {
return {
pushEvent: hook.pushEvent.bind(hook),
pushEventTo: hook.pushEventTo.bind(hook),
handleEvent: hook.handleEvent.bind(hook),
removeHandleEvent: hook.removeHandleEvent.bind(hook),
upload: hook.upload.bind(hook),
uploadTo: hook.uploadTo.bind(hook),
};
}
/**
* Wrap a component in the ReactPhxProvider, injecting the hook functions
* into context and rendering the component with the given props and children.
*/
export function getComponentTree(
Component: ComponentType<any>,
props: Record<string, unknown> & HookProps,
children: ReactNode[],
): React.JSX.Element {
const componentInstance = createElement(Component, props, ...children);
const withBoundary = createElement(
ReactPhxErrorBoundary,
{ componentName: Component.displayName || Component.name },
componentInstance,
);
return createElement(
ReactPhxProvider,
{
pushEvent: props.pushEvent,
pushEventTo: props.pushEventTo,
handleEvent: props.handleEvent,
removeHandleEvent: props.removeHandleEvent,
upload: props.upload,
uploadTo: props.uploadTo,
children: withBoundary,
},
);
}