I'm currently working on a React.js-based app. Lets say we have a Header component in React with a small logo component inside it that should only be displayed at mobile resolution levels. I'm passing an isMobile prop from the parent component. This prop is based on:
const mql = global.matchMedia(`(min-width: 768px)`);
mql.addListener(() => this._mediaQueryChanged());
this.setState({
mql: mql,
isMobile: !mql.matches
});
_mediaQueryChanged() {
this.setState({
isMobile: !this.state.mql.matches
});
}
<Header isMobile={this.state.isMobile} />
And in Header:
render() {
const {isMobile} = this.props;
const containerClass = classNames('header-component', {
'is-mobile': isMobile
});
return (
<header className={containerClass}>
{
isMobile &&
(
<section className="mobile-header">
<Button className="toggle-menu" onClick={() => this._toggleMenu()}>
<Icon name="menu" />
</Button>
<Logo className="header-logo" />
</section>
)
}
<span>login</span>
</header>
);
}
and if mql matches then it is not mobile. My question is: should I pass this param and re-render the component every time we change Media queries? During re-render hide/show logo component? Or just use CSS to show/hide it and the component will be mounted there all the time. No re-renders tho.
Thoughts?
I agree this may be a job for just CSS.
.header-class .logo {
display:none;
}
@media only screen and (min-width: 768px) {
.header-class .logo {
display:block;
}
}
I think it depends on what you're trying to achieve. If you have universal rendering with critical path CSS extraction and trying to shave milliseconds go for the react-only solution. Otherwise css-only solution will do but equally as well as the react-only solution because you're probably re-rendering already. That sneaky isMobile has just triggered a render somewhere else in your codebase (or will in the future); plus, you've just lost the extensibility of that react offers.