6

How to specify className attribute for div which contains 'hello world':

<div dangerouslySetInnerHTML={{__html: '<div>hello world</div>'}} />

One way is to set is to outer div like so:

<div dangerouslySetInnerHTML={{__html: '<div>hello world</div>'}} className='class-name'/>

and then in css style the child:

.class-name div {
  (css stuff here)
}

But I want to set className directly to the div with 'hello world'


EDIT: Adding class name to injected html does not solve the problem, for example:

let content = '<div class="class-name">hello world</div>'
<div dangerouslySetInnerHTML={{__html: content}}

does not work, because in case same content is used many times then CSS collisions occur (I am using style-loader with CSS modules on)

Rifky Niyas
  • 1,737
  • 10
  • 25
Daniel
  • 161
  • 2
  • 11
  • As you updated your question, may you clarify if your class names are static or dynamic? – lumio Apr 08 '19 at 14:59
  • @lumio dynamic, for example CSS modules convert className into something like this: componentName_className__1eKtRuyKh – Daniel Apr 08 '19 at 15:09

2 Answers2

1

I came across this question after 2 years and I wanted to achieve the exact same results. I didn't find any accurate answers here but I came up with a solution thanks to @jash8506 due to the brilliant answer to this question.

We have to utilize two react hooks

  1. useRef
  2. useLayoutEffect

According to the documentation basically, useRef can be used to access the DOM elements in React and useLayoutEffect can be used to read layout from the DOM and synchronously re-render.

We can access the firstChildElement in the container div and add classes to it's classList

Here is how the completed code looks like

const containerRef = useRef();

useLayoutEffect(()=>{
  if (containerRef.current){
    containerRef.current.firstElementChild.classList.add('class-name');
  }
});

return (
  <div ref={elRef} dangerouslySetInnerHTML={{__html: '<div>hello world</div>'}} />
)
Rifky Niyas
  • 1,737
  • 10
  • 25
0
<div className="post-excerpt" dangerouslySetInnerHTML={{ __html: post.excerpt}}/>
Zakir Sajib
  • 293
  • 2
  • 7
  • 16