UNPKG

@j2inn/app-react

Version:

React implementation of the j2inn-app framework

48 lines (47 loc) 1.95 kB
import { Fragment as _Fragment, jsx as _jsx } from "react/jsx-runtime"; /* * Copyright (c) 2022, J2 Innovations. All Rights Reserved */ import { toStringProps } from '@j2inn/app'; import React, { useEffect, useRef } from 'react'; /** * Renders a web component in a react component and passes * down properties into the web component. */ export const WebComponent = (props) => { // Track the web component reference so we can use it. const ref = useRef(); const { name, ...wcProps } = props; useEffect(() => { const wc = ref.current; if (wc) { // Pass all the properties down into the web component as properties. for (const propName of Object.keys(wcProps)) { wc[propName] = wcProps[propName]; } // Invoke a custom callback when properties have been changed. // This is done because there's no hook in a web component for detecting when properties // change. if (typeof wc.propertiesChangedCallback === 'function') { wc.propertiesChangedCallback(wcProps); } } }, Object.values(wcProps)); useEffect(() => { const wc = ref.current; if (wc) { // Invoke a custom callback when properties have been first loaded. // This is only invoked once. if (typeof wc.propertiesInitializedCallback === 'function') { wc.propertiesInitializedCallback(wcProps); } } }, []); return (_jsx(_Fragment, { children: React.createElement(name, { ref, // Also try passing the properties as attributes // (although this does limit the values to strings). By doing this, the web component will // also get the `attributeChangedCallback()` invoked. ...toStringProps(wcProps), }) })); };