'How can i be able to apply style on template literals
I am using template literals to show my data in react, but I want to style that email, how can I be able to apply inline style on that template literal, is there any possibility to do it?
{`${eachCustomer?.name} <${eachCustomer?.email}>`}
Solution 1:[1]
Template literals output strings. Styles apply to elements. The idea of applying style to a template literal doesn't make sense.
If you want to apply styles, then create elements. Use JSX. e.g.
return <>
{eachCustomer?.name} <<StyledEmailComponent>{eachCustomer?.email}</StyledEmailComponent>>
</>;
Solution 2:[2]
Try this
{`${eachCustomer?.name} ${eachCustomer?.email ? <span style={{ color: 'red' }}>{eachCustomer.email}</span> : null}`}
Solution 3:[3]
I'd like to leave this answer here for those looking to style dynamic strings made using template literals. It's possible to use a tag function and assign a css class only to the variables in the template string, thus styling dynamic values only.
export const highlight = (strings: TemplateStringsArray, ...values: (string | number)[]) => {
let str = '';
strings.forEach((string, i) => {
str += `${string} <span class='hl'>${values[i] || ''}</span>`;
});
return str;
};
You can then use it like this in React:
<p
dangerouslySetInnerHTML={{
__html: highlight`User ${userAddress} claimed ${tokenAmount} ${token.symbol}.`
}}
/>
This article by Wes Bos helped me solve that.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Quentin |
| Solution 2 | Hasareli Fernando |
| Solution 3 | Arthur Burgan |
