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({
rende
A good solution to load multiple atributes from a js class to the document body can be:
componentWillMount: function(){
for(i in styles.body){
document.body.style[i] = styles.body[i];
}
},
componentWillUnmount: function(){
for(i in styles.body){
document.body.style[i] = null;
}
},
And after you write your body style as long as you want:
var styles = {
body: {
fontFamily: 'roboto',
fontSize: 13,
lineHeight: 1.4,
color: '#5e5e5e',
backgroundColor: '#edecec',
overflow: 'auto'
}
}
Assuming your body tag isn't part of another React component, 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
method, and cancel it at componentWillUnmount
:
componentWillMount: function(){
document.body.style.backgroundColor = "green";
}
componentWillUnmount: function(){
document.body.style.backgroundColor = null;
}
Even if you can set body styles from react with the provided answer, I prefer if a component is only responsible for setting its own style.
In my case there was an alternative solution. I needed to change the body backgroundColor. This could easily be achieved without changing the body style in a react component.
First I added this style to the index.html header.
<style>
html, body, #react-app {
margin: 0;
height: 100%;
}
</style>
Then, in my outermost component, I set the backgroundColor to the needed value and the height to 100%.
The best way to load or append extra classes is by adding the code in componentDidMount().
Tested with react and meteor :
componentDidMount() {
var orig = document.body.className;
console.log(orig); //Just in-case to check if your code is working or not
document.body.className = orig + (orig ? ' ' : '') + 'gray-bg'; //Here gray-by is the bg color which I have set
}
componentWillUnmount() {
document.body.className = orig ;
}