Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to pass style using dangerouslySetInnerHTML in React

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.

like image 399
H.Sdq Avatar asked Nov 29 '18 13:11

H.Sdq


People also ask

How do I use dangerouslySetInnerHTML in React JS?

dangerouslySetInnerHTML is a property that you can use on HTML elements in a React application to programmatically set their content. Instead of using a selector to grab the HTML element, then setting its innerHTML , you can use this property directly on the element.

What can I use instead of dangerouslySetInnerHTML in React?

However, if the application or site accepts multiple users' data input, you should be concerned. However, apart from that, there is one alternative to using dangerouslySetInnerHTML, simply setting innerHTML of a React HTML element using vanilla JS instead.

Does innerHTML work in React?

innerHTML prop is risky because it is easy to expose your users to a cross-site scripting (XSS) attack. React provides dangerouslySetInnerHTML as a replacement for innerHTML prop to remind yourself that it is dangerous. Therefore, you should use dangerouslySetInnerHTML prop instead of innerHTML prop.


1 Answers

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.

like image 197
Bhojendra Rauniyar Avatar answered Sep 20 '22 11:09

Bhojendra Rauniyar