Code:
function App() {
const html = '<p>Some text <br/><span>Some text</span></p>';
return <div dangerouslySetInnerHTML={{ __html: html }} />;
}
export default App;
I want to style the <span> element using Tailwind CSS. How can I do it?
Code:
function App() {
const html = '<p>Some text <br/><span>Some text</span></p>';
return <div dangerouslySetInnerHTML={{ __html: html }} />;
}
export default App;
I want to style the <span> element using Tailwind CSS. How can I do it?
On
A simpler solution may be to use the following:
function App() {
const html = '<p>Some text <br/><span class="text-lg">Some text</span></p>';
return <div dangerouslySetInnerHTML={{ __html: html }} />;
}
export default App;
Imp points:
class instead of className; otherwise, it won't work as it is HTML and not JSX.data.json, ensure to include it in the content setting of tailwind.config.js. So that, Tailwind CSS can detect and include those classes in the CSS.
Tailwind in general requires setting classes on the element you wish to apply styles to. It's not a good pattern, but you can use arbitrary variants and child selectors.
For example:
Other options could include:
Define a 'normal' css class, attach it to the wrapper and style the spans inside the class:
Avoid using dangerouslySetInnerHTML, find another way to tackle this problem entirely (if possible)
Use a html parser (or the DOM) and either mutate the string and re-render as a string, or, render react components from the results. Here's that in vanilla javascript (out of the context of react):