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?
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.
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.
Deprecations. react-dom : ReactDOM.render has been deprecated. Using it will warn and run your app in React 17 mode.
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; }
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