Specifically for ReactJS and responsive frameworks that show/hide elements based on width like Bootstrap.
Because ReactJS has a virtual DOM I am presuming doing the DOM manipulation is faster and in the end a bit easier to debug because you are not trying to think which parts are display:none and there are less elements to debug. It was also easier to me to think that way because of my programming background rather than CSS.
I haven't dealt with too much performance testing yet on ReactJS (that's a few chapters down) but what is better from an engineering standpoint.
Code wise it looks like this...
constructor(props) {
super(props)
this.updateStatesBasedOnWindowSize =
this.updateStatesBasedOnWindowSize.bind(this)
this.state = {
smallDeviceNavigation: false,
sideNavVisible: false,
}
}
componentWillMount() {
this.updateStatesBasedOnWindowSize()
}
componentDidMount() {
window.addEventListener("resize", this.updateStatesBasedOnWindowSize)
}
componentWillUnmount() {
window.removeEventListener("resize", this.updateStatesBasedOnWindowSize)
}
/**
* This will trigger a state change based on the device size.
*/
updateStatesBasedOnWindowSize() {
const w = window,
d = document,
documentElement = d.documentElement,
body = d.getElementsByTagName('body')[0],
width = w.innerWidth ||
documentElement.clientWidth || body.clientWidth
if (width >= 576) {
if (this.state.smallDeviceNavigation) {
this.setState({ smallDeviceNavigation: false })
}
if (!this.state.sideNavVisible) {
this.setState({ sideNavVisible: true })
}
} else {
if (!this.state.smallDeviceNavigation) {
// Force hide the side
// nav if the smallDeviceNavigation was false before.
this.setState({ sideNavVisible: false })
}
if (!this.state.smallDeviceNavigation) {
this.setState({ smallDeviceNavigation: true })
}
}
}
Then in the components I just check this.state accordingly. I get the advantage that I am dealing with the state based on a logical name rather than physical widths and breakpoints I am not dealing with.
Mind you this is for show/hide hence I emphasized it earlier. Layouts based on CSS I just left alone and let bootstrap grid deal with it. But menus and navs I did the DOM manipulation.
windowobject is outside of the virtual dom, so show/hide via DOM computed properties causes reflow and repaint.