Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ReactJS dangerouslySetStyle?

Tags:

reactjs

I am using ReactJS and am aware of dangerouslySetInnerHTML but I want to be able to set an element's style attribute to a raw string. I've searched and had a look through the React source but I can't find anything.

Is there a way to do this?

like image 268
Robin Elvin Avatar asked Jan 30 '15 14:01

Robin Elvin


2 Answers

You have to manually set the attribute on the dom node to do this. The simplest way would be with a wrapper component:

<CustomAttribute tag="div" dangerouslySetAttributes={{style: 'color:red'}}>
  red text
</CustomAttribute>

And the actual component

var DSA = 'dangerouslySetAttributes';
var CustomAttribute = React.createClass({
  setAttributes: function(oldAttrs, attrs){
    var el = this.getDOMNode();
    Object.keys(attrs).forEach(function(key){
      if (oldAttrs[key] !== attrs[key]) 
        el.setAttribute(key, attrs[key]);
    });
  },
  componentDidMount: function(){ 
    this.setAttributes({}, this.props[DSA]);
  },
  componentWillReceiveProps: function(nextProps){ 
    this.setAttributes(this.props[DSA], nextProps[DSA]);
  },
  render: function(){
    var Tag = this.props.tag || 'div';
    return <Tag>{this.props.children}</Tag>
  },
});

*not tested

like image 91
Brigand Avatar answered Sep 18 '22 00:09

Brigand


Why don't you set the entire markup, including styles, in dangerouslySetInnerHTML, like such:

var markup = "<div style='"+dynamicStyleString+"'>Content</div>"

<div dangerouslySetInnerHTML={{__html: markup}}></div>

That should get the job done

like image 45
spitfire109 Avatar answered Sep 19 '22 00:09

spitfire109