Skip to content

Support Class Functions as React Props #221

New issue

Have a question about this project? # for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “#”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? # to your account

Open
wants to merge 2 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 10 additions & 0 deletions packages/core/src/transforms/function.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
import { toCamelCase } from "../utils"

import { Transform } from "./index"

const function_: Transform<(...args: unknown[]) => unknown> = {
Expand All @@ -13,6 +15,14 @@ const function_: Transform<(...args: unknown[]) => unknown> = {
// @ts-expect-error
return global[value]
}

const functionName = toCamelCase(attribute)

//@ts-expect-error
if (typeof element !== "undefined" && functionName in element.container) {
// @ts-expect-error
return element.container[functionName]
}
})()

return typeof fn === "function" ? fn.bind(element) : undefined
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -363,4 +363,56 @@ describe("react-to-web-component 1", () => {
button.click()
})
})

it("Supports class function to react props", async () => {

const ClassGreeting: React.FC<{ name: string, sayHello: () => void }> = ({ name, sayHello }) => (
<div>
<h1 id="class-greeting-text">Hello, {name}</h1>
<button id="click-class-greeting" onClick={() => sayHello()}>Click me</button>
</div>
)

const WebClassGreeting = r2wc(ClassGreeting, {
props: {
name: "string",
sayHello: "function",
},
})

customElements.define("class-greeting", WebClassGreeting)

document.body.innerHTML = `<class-greeting name='Christopher'></class-greeting>`

const el = document.querySelector("class-greeting") as HTMLElement & { sayHello?: () => void };

el.sayHello = function () {
const nameElement = el.querySelector("h1") as HTMLElement;
nameElement.textContent = "Hello, again";
}

el.setAttribute("say-hello", "sayHello");

await new Promise((resolve, reject) => {
const failIfNotClicked = setTimeout(() => {
reject()
}, 1000)

setTimeout(() => {
const button = document.body?.querySelector(
"#click-class-greeting",
) as HTMLButtonElement;

button.click()

setTimeout(() => {
const element = document.body.querySelector("h1")
expect(element?.textContent).toEqual("Hello, again")
clearTimeout(failIfNotClicked)
resolve(true)
}, 0)
}, 0)
})
})

})