Rico Kahler
Rico Kahler

Reputation: 19202

How to stop a React render on media queries

I have existing CSS (therefore, I should consider it) that includes media queries whether to display an element. The CSS works as expected but the problem is that React still re-renders and re-structures the DOM even when the media query causes the element not to be re-rendered anyway.

Is there any way to tell react not to render? Is there a way to detect the media query in React and then not render if the media query says not to?

Upvotes: 1

Views: 949

Answers (1)

Imtiaz
Imtiaz

Reputation: 101

You could use matchMedia and return false from shouldComponentUpdate

Something like the following depending on your use-case

shouldComponentUpdate(nextProps) {
    return window.matchMedia('(min-width: 768px)').matches
}

Upvotes: 3

Related Questions