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?
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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With