Skip to content

Instantly share code, notes, and snippets.

@temoncher
Last active January 22, 2024 13:42
Show Gist options
  • Save temoncher/4f246af5425c12ee52575e6661db54c2 to your computer and use it in GitHub Desktop.
Save temoncher/4f246af5425c12ee52575e6661db54c2 to your computer and use it in GitHub Desktop.
jsx tagged template for inline text
/**
* @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