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?
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:
const App = () => {
const html = '<p>Some text <br/><span>Some text</span>';
return (
<div
dangerouslySetInnerHTML={{__html: html}}
className="[&>p>span]:text-lg"
/>
);
}
Other options could include:
Define a 'normal' css class, attach it to the wrapper and style the spans inside the class:
// index.css
.wrapper span {
color: red;
}
// react component
import './index.css';
...
const App = () => {
const html = '<p>Some text <br/><span>Some text</span>';
return (
<div
dangerouslySetInnerHTML={{__html: html}}
className="wrapper"
/>
);
}
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):
const div = document.createElement('div')
div.innerHTML = '<p>Some text <br/><span>Some text</span>'
div.querySelectorAll('span').forEach(span => span.classList.add('text-lg'))
console.log(div.innerHTML) // <p>Some text <br><span class="text-lg">Some text</span></p>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With