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)
<div className="post-excerpt" dangerouslySetInnerHTML={{ __html: post.excerpt}}/>
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
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>'}} />
)
Before you continue reading: Ask yourself why you need dangerouslySetInnerHTML
! This is not meant to be used and if so, use a sanitizer.
/* React with HTML context */
<div dangerouslySetInnerHTML={{__html: '<div class="class-name">hello world</div>'}} />
You can simplify this however in a safe way:
/* React context only */
<div className="class-name">hello world</div>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.