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>)
}
)}
Use the classList. add() method to add a class to the body element, e.g. document. body. classList.
Right now you should use classes in React if you need to use "advanced" component lifecycle methods like shouldComponentUpdate() or such. Previously class components were used to handle local state in them. Right now we have Hooks API which allows to use state in a more elegant way and without need of class components.
If you want to add a class ( className ) to the body tag of a a NextJS page, you'll need to add it via JavaScript in the useEffect (or componentDidMount if you're using class-based components) Lifecycle function. This adds TailWindCSS's font-light and text-gray-700 classes to the body tag.
className. To specify a CSS class, use the className attribute. This applies to all regular DOM and SVG elements like <div> , <a> , and others. If you use React with Web Components (which is uncommon), use the class attribute instead.
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');
}
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.
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