Wednesday, June 5, 2024
 Popular · Latest · Hot · Upcoming
180
rated 0 times [  185] [ 5]  / answers: 1 / hits: 13637  / 10 Years ago, sat, november 1, 2014, 12:00:00

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>)
}
)}

More From » reactjs

 Answers
2

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.


[#41535] Friday, October 31, 2014, 10 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
christianu

Total Points: 481
Total Questions: 124
Total Answers: 99

Location: Trinidad and Tobago
Member since Thu, Dec 1, 2022
2 Years ago
;