Last active
December 11, 2019 13:16
-
-
Save WarHatch/c8d368edfc132798bdaf6648451eebb9 to your computer and use it in GitHub Desktop.
[TypeScript] text-patched html element function on an existing element
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
type IHtmlFunctionCallBuilder<T extends (...args: any) => void> = (func: T, funcArgs: Parameters<T>) => string | |
const htmlFunctionCallBuilder: IHtmlFunctionCallBuilder<(...args: any) => void> = (func, funcArgs) => { | |
let parsedArgs = JSON.stringify(funcArgs); | |
return `${func.name}(${parsedArgs});` | |
} | |
const renderToHTMLWithFunctions = (props: IButtonData) => { | |
// Create HTML element | |
const html = ReactDOMServer.renderToString(Button(props)); | |
// Assuming HTML is correct the string will be <elemType ... | |
const elemStart = html.split(/\b/)[0] + html.split(/\b/)[1]; | |
// We will separate HTML text right after elemType | |
const elemEnd = html.substring(elemStart.length); | |
// And will put in the functions in between | |
const functionCodeStart = " onClick=\'" | |
const functionCodeEnd = "\' " | |
let htmlWithFunc = functionCodeStart; | |
if (props.callsback === true) htmlWithFunc += htmlFunctionCallBuilder(functions.exampleButtonCallback, { data: "test" }); | |
htmlWithFunc += functionCodeEnd; | |
return elemStart + htmlWithFunc + elemEnd; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment