Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In Tailwind CSS, how to style elements while using dangerouslySetInnerHTML in ReactJS?

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?

like image 281
Lenur Avatar asked Jul 24 '26 22:07

Lenur


1 Answers

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>
    
like image 103
aaronmoat Avatar answered Jul 26 '26 14:07

aaronmoat