Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 963
Giant Elk Avatar asked Aug 24 '14 18:08

Giant Elk


People also ask

Can you use the DOM in React?

React implements a browser-independent DOM system for performance and cross-browser compatibility. We took the opportunity to clean up a few rough edges in browser DOM implementations. In React, all DOM properties and attributes (including event handlers) should be camelCased.

How do I change my DOM in React?

To manipulate a React component's "actual DOM" you can grab a reference of it using getDOMNode() . Then your Foobar component could set the className based on this. props.

Is React DOM deprecated?

Deprecations. react-dom : ReactDOM.render has been deprecated. Using it will warn and run your app in React 17 mode.


1 Answers

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; } 
like image 197
yarden Avatar answered Sep 18 '22 08:09

yarden