I need to render different components based on the screen size -
If the screen is 1012px or under then setComponent('box');
If the screen is 1460px or under then setComponent('info);
Else if the screen is above 1460px then setComponent('both');
This is how I'm currently doing it -
if (typeof window !== 'undefined' && showComponents) {
window.matchMedia('(max-width: 1012px)').addEventListener('change', (event) => {
if (event.matches) {
setComponent('box');
}
});
window.matchMedia('(max-width: 1460px)').addEventListener('change', (event) => {
if (event.matches) {
setComponent('info');
}
});
window.matchMedia('(min-width: 1460px)').addEventListener('change', (event) => {
if (event.matches) {
setComponent('both');
}
});
}
Before this, I was using window.innerWidth however I read that matchMedia is a better solution to this. But looking at the code above, I am not sure if there is a cleaner way of writing it. Also do the listeners need to be removed?