Last active
January 22, 2024 13:42
-
-
Save temoncher/4f246af5425c12ee52575e6661db54c2 to your computer and use it in GitHub Desktop.
jsx tagged template for inline text
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
/** | |
* @example | |
* | |
* const red = (text) => <span style={{ backgroundColor: 'red', color: 'white', padding: '8px' }}>{text}</span>; | |
* | |
* return ( | |
* <> | |
* {jsxt`Displaying some ${red('red text')} here`} | |
* </> | |
* ); | |
*/ | |
export const jsxt = (strings: TemplateStringsArray, ...holes: React.ReactNode[]) => { | |
const elements = [] as React.ReactNode[]; | |
let currentIndex = 0; | |
let accumulationString = ""; | |
while (currentIndex < strings.length) { | |
accumulationString += strings[currentIndex]; | |
const nextHole = holes[currentIndex]; | |
if (typeof nextHole === "string" || typeof nextHole === "number") { | |
accumulationString += nextHole; | |
} else { | |
elements.push(accumulationString); | |
if (nextHole) elements.push(nextHole); | |
accumulationString = ""; | |
} | |
currentIndex++; | |
} | |
return <>{elements}</>; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment