The reactToWebComponent function can wrap React components that rely on external libraries (such as Material UI's ThemeProvider or Button) to expose them as Web Components. When defining the component via reactToWebComponent, you must specify the expected types for the props in the configuration object.
Note that when passing values via HTML attributes, you should use kebab-case (e.g., color-mode instead of colorMode) to map to the React component's props.
import { Button } from "@mui/material"
import { ThemeProvider, createTheme } from "@mui/material/styles"
interface GreetingProps {
name: string
description: string
colorMode?: "light" | "dark" | undefined
buttonVariant?: "contained" | "text" | "outlined" | undefined
}
export const Greeting = ({
name,
description,
colorMode = "light",
buttonVariant = "text",
}: GreetingProps) => {
const themeMode = createTheme({
palette: {
mode: colorMode,
},
})
return (
<ThemeProvider theme={themeMode}>
<main>
<h1>Hello, {name}</h1>
<p>{description}</p>
<Button variant={buttonVariant}>This is the button</Button>
</main>
</ThemeProvider>
)
}
const WebGreeting = reactToWebComponent(Greeting, {
props: {
name: "string",
description: "string",
colorMode: "string",
buttonVariant: "string",
},
})
customElements.define("web-greeting", WebGreeting)