Perhaps I am suppposed to work it with ComponentWillMount or ComponentDidMount
Yes, you need to listen for resize
event and update internal state on change. You can do it by adding event handler when component mounts. Try full example here.
class App extends React.Component {
constructor(props) {
super(props);
this.state = {
isDesktop: false //This is where I am having problems
};
this.updatePredicate = this.updatePredicate.bind(this);
}
componentDidMount() {
this.updatePredicate();
window.addEventListener("resize", this.updatePredicate);
}
componentWillUnmount() {
window.removeEventListener("resize", this.updatePredicate);
}
updatePredicate() {
this.setState({ isDesktop: window.innerWidth > 1450 });
}
render() {
const isDesktop = this.state.isDesktop;
return (
<div>
{isDesktop ? (
<div>I show on 1451px or higher</div>
) : (
<div>I show on 1450px or lower</div>
)}
</div>
);
}
}