8

I'm injecting html in my react component using dangerouslySetInnerHTML in a format like this :

<div 
    className="mt-2 col variant-attr-cell p-0" 
    dangerouslySetInnerHTML = { { 
        __html: JSON.parse(attrs[i].snippet).snippet.replace("{text}", 
        attrs[i].choices[j].visualization_data) 
    } } 
>
</div>

and it works fine but I'm trying to pass style to the injected html at the same time but don't know how! I'm trying to add different styles to the injected html based on the api I get, something like this:

height: 12px;
width: 12px;
border-radius: 50%;
display: inline-block;
margin: 0 4px;

FYI the injected html is something like this mostly:

<span></span>

and the styles must be added to this and not the container div! Any solution is appreciated, thanks.

Smarticles101
  • 1,822
  • 1
  • 14
  • 28
H.Sdq
  • 797
  • 3
  • 12
  • 22

5 Answers5

4

You can still add the desired style. Just add another props style:

const styleObj = {
  color: 'white',
  backgroundColor: 'red'
};


<div 
  className="mt-2 col variant-attr-cell p-0" 
  dangerouslySetInnerHTML = {
    { __html: JSON.parse(attrs[i].snippet).snippet
        .replace("{text}", attrs[i].choices[j].visualization_data)
     } 
   }
   style={styleObj}
>
</div>

If you're trying to add style inside the element that resides in the html, then you should have their styles there in the html itself.

Bhojendra Rauniyar
  • 83,432
  • 35
  • 168
  • 231
3

I managed to do this by adding a ref to the container and using the useLayoutEffect hook.

const elRef = useRef();

useLayoutEffect(()=>{
  if (elRef.current){
    elRef.current.firstElementChild.style.height = '12px';
    // set other style attributes
    ...
  }
});

return <div
  ref={elRef}
  dangerouslySetInnerHTML={yourHTML}
/>

This assumes you only want to style the first child of your container, but you could use a similar approach for multiple children.

jash8506
  • 51
  • 1
2

You can easily style element in dangerousHTML like this style='background-color:red' instead style={{backgroundColor:'red'}}

32lp1
  • 21
  • 1
1

Since I get the HTML from API, I set the style attribute for the HTML with a static value in the database and replaced the static value from API in my component!

H.Sdq
  • 797
  • 3
  • 12
  • 22
0

This isn't the cleanest way of doing it but this works for me:

  const cssAppliedContent = body => `
    <div>
      <style>
        body {
          padding: 0;
          margin: 0;
          font-size: 14px;
        }
      </style>
      ${body}
    <div>
    `;

  // further down in your code
  <div
    className={'html'}
    style={{ lineHeight: 1.6 }}
    dangerouslySetInnerHTML={{
      __html: cssAppliedContent(yourHtml),
    }}
  />
Jeff
  • 11
  • 2