12

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() {
      if (this.state.touchMode === 2) {
          $('body').addClass('touchMode');
      }

      return (<div> etc /div>)
    }
  )}
1
  • 1
    Why would you use Jquery when this can be achieved by plain javascript? Commented Feb 8, 2017 at 7:44

2 Answers 2

22

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');
}
Sign up to request clarification or add additional context in comments.

Comments

9

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

var globalEvents = new EventEmitter();

var App = 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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.