Skip to content

Instantly share code, notes, and snippets.

@hyousi
Last active May 24, 2021 08:30
Show Gist options
  • Save hyousi/d7d90c275f7693158a6a882b2e42d134 to your computer and use it in GitHub Desktop.
Save hyousi/d7d90c275f7693158a6a882b2e42d134 to your computer and use it in GitHub Desktop.
React tagged template
interface HighlightTextConfig {
highlightStyle: React.CSSProperties;
baseStyle: React.CSSProperties;
}
export const highlightText = (config?: HighlightTextConfig) => (
literals: TemplateStringsArray,
...substitutions: string[]
) => (
<div style={config?.baseStyle ?? {}}>
{literals.map((literal, i) => (
<>
{literal}
<span style={config?.highlightStyle ?? {}}>{substitutions[i]}</span>
</>
))}
</div>
);
// usage
const action = "send a message";
const user = "Pingpong";
const description = highlightText(
styles.text,
styles.highlight
)`You’re going to ${action} to ${user}. Please confirm?`;
// in the render method
<Text>{description}</Text>;
// hof
const description = (user, action, styles) => highlightText(
styles.text,
styles.highlight
)`You’re going to ${action} to ${user}. Please confirm?`;
// in the render method
<Text>{description('Pingpong', 'Send a message', styles)}</Text>;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment