Skip to content Skip to sidebar Skip to footer

When, Where And How To Add Class To The Document.body When Using React.js

Currently I am doing this, but this is not the react.js way, right? Is render() the right place? What is the alternative? var App = React.createClass({ render: function() {

Solution 1:

Well ideally adding a class to the body would break the encapsulation that React components provide and fiddling with the DOM outside React could cause trouble if the body gets re-rendered. If possible, rather than adding the class to the document body, I would just add it to a component root element that React manages.

But to answer your question, you could do that way, but how often is your this.state.touchMode would change? If it's something that only changes during mount/unmount of the component, you can do it in componentWillMount (so that it only runs once when component mount, rather than every single time during render):

componentWillMount: function(){
    document.body.classList.add('touchMode');
},
componentWillUnmount: function(){
    document.body.classList.remove('touchMode');
}

Solution 2:

It's best to keep this logic outside of your component. Event emitters are a good way to abstract this.

var globalEvents = newEventEmitter();

varApp = React.createClass({
  setTouchMode: function(touchMode){
     globalEvents.emit('touchModeChange', touchMode);
  },
  render: ...
});

// outside any react class
globalEvents.on('touchModeChange', function(mode){
  if (mode === 2) {
    $('body').addClass('touchMode');
  }
  else {
    $('body').removeClass('touchMode');
  }
});

If it really needs to be part of the state of one or more components, they can also listen to the event and update their state in the handler.

Post a Comment for "When, Where And How To Add Class To The Document.body When Using React.js"