Giant Elk Giant Elk - 2 months ago 17
React JSX Question

Trying to use React.DOM to set body styles

How can I use React.DOM to change styles on HTML

body
?

I tried this code and it's not working:

var MyView = React.createClass({
render: function() {
return (
<div>
React.DOM.body.style.backgroundColor = "green";
Stuff goes here.
</div>
);
}
});


If you execute this from the browsers console it works (but I need it working in ReactJS code):
document.body.style.backgroundColor = "green";


Also see this question for similar but different solution:
Change page background color with each route using ReactJS and React Router?

Answer

assuming your body tag isn't part of another react coponent, just change it as usual-

document.body.style.backgroundColor = "green";
//elsewhere..
return (
  <div>
    Stuff goes here.
  </div>
);

it's recommended to put it at componentWillMount function, and cancel it at componentWillUnmount:

componentWillMount: function(){
    document.body.style.backgroundColor = "green";
}
componentWillUnmount: function(){
    document.body.style.backgroundColor = null;
}
Comments