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

2.6k Views Asked by At

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?

3

There are 3 best solutions below

1
aaronmoat On

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>
    
0
Dipen Dadhaniya 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:

  • In the string, ensure to use class instead of className; otherwise, it won't work as it is HTML and not JSX.
  • If you are importing the HTML string from some other file, e.g., 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.
0
Y U K I M U R A On

if you want to set same styles on all the span elements, you can use string.replaceAll method on spans, like this:

 const html = '<p>Some text <br/><span>Some text</span>';
html.replaceAll('<span', '<span className='text-lg')