UNPKG

@playcanvas/react

Version:

A React renderer for PlayCanvas – build interactive 3D applications using React's declarative paradigm.

44 lines 1.52 kB
import { useLayoutEffect, useRef } from "react"; import { useParent } from "./use-parent"; import { useApp } from "./use-app"; export const useComponent = (ctype, props) => { const componentRef = useRef(null); const parent = useParent(); const app = useApp(); useLayoutEffect(() => { if (!ctype) { return; } if (parent) { // Only add the component if it hasn't been added yet if (!componentRef.current) { const clonedOpts = { ...props }; componentRef.current = parent.addComponent(ctype, clonedOpts); } // Do not throw an error if the component already exists } return () => { const comp = componentRef.current; componentRef.current = null; if (!app || !app.root) return; if (comp) { if (app.systems[ctype]) parent.removeComponent(ctype); } }; }, [app, parent, ctype]); // Update component props useLayoutEffect(() => { if (!ctype) { return; } const comp = componentRef.current; // Ensure componentRef.current exists before updating props if (!comp) return; const filteredProps = Object.fromEntries(Object.entries(props).filter(([key]) => key in comp)); Object.assign(comp, filteredProps); }, [props, ctype]); }; //# sourceMappingURL=use-component.js.map