-
Notifications
You must be signed in to change notification settings - Fork 20
Framework Integrations
A (not so) comprehensive list of dos and don'ts for using web components inside your preferred framework.
There are special considerations when using web components inside of a React application. Namely, React uses HTML attributes to pass data from a parent component to a child. This works for string values but not for booleans, arrays, objects, etc. Native HTML Elements use attribute values for strings but javascript setters for more complex data.
❌ Don't
function App() {
const [isWarning, setIsWarning] = useState(false);
return (
<>
<pf-button warning={isWarning}>Start trial</pf-button>
</>
);
}
The above example will not work due because isWarning
is a boolean value that JSX renders as warning=""
.
Similarly with events, React cannot listen for events coming from custom elements because of it's use of the Synthetic Events system.
❌ Don't
function App() {
const [isWarning, setIsWarning] = useState(false);
return (
<>
<pf-switch onChange={() => setIsWarning(!isWarning)}></pf-switch>
</>
);
}
Lit provides a utility wrapper createComponent which makes a React component wrapper for a custom element class through @lit-labs/react
. The wrapper correctly passes React props to properties accepted by the custom element and listens for events dispatched by the custom element.
✅ Do
import * as React from 'react';
import { createComponent } from '@lit-labs/react';
import { PfSwitch } from '@patternfly/elements/pf-switch/pf-switch.js';
export const SwitchComponent = createComponent({
tagName: 'pf-switch',
elementClass: PfSwitch,
react: React,
events: {
onChange: 'change'
},
});
This makes it more convenient to work with our Lit-based web components in React Components.
import { SwitchComponent } from './Switch.js';
function App() {
const [isWarning, setIsWarning] = useState(false);
return (
<>
<SwitchComponent onChange={() => setIsWarning(!isWarning)}></SwitchComponent>
</>
);
}
Visit the pfe-react-wrappers-demo.
Questions? Please contact [email protected]. Please review our Code of Conduct