whoMe
whoMe

Reputation: 247

Listening for JavaScript Media Queries in React

I am trying to implement the media query concept found here in React. With what's shown below I am getting the following:

TypeError: isMobile.addListener is not a function
function App() {
    // Saving current page to state 
    let location = useLocation();

    useEffect(() => {
        useStore.setState({ currentPage: location })
    }, [location]);

    // Check if viewing in landscape on mobile
    const isMobile = window.matchMedia("only screen and (max-width: 830px)").matches;

    const setOrientation = (e) => {
        if (e.isMobile) {
            if (window.innerHeight > window.innerWidth){
                // is not landscape
            } else{
                // is landscape
            }
        }
    }

    useEffect(() => {
        setOrientation(isMobile)
        isMobile.addListener(setOrientation)

        return () => isMobile.removeEventListener(setOrientation)
    }, []);

    return (
        <div className="App"></div>
    );
}

export default App;

What am I doing wrong?

Upvotes: 1

Views: 1504

Answers (2)

Flavio
Flavio

Reputation: 546

It's because you are setting const isMobile to type Boolean (true/false) instead of the upper level Object (function) window.matchMedia('string_query')

Try something like this:

const isMobile = window.matchMedia("only screen and (max-width: 830px)")

typeof isMobile
"object"

isMobile.matches
true

function handleTabletChange(e) {
  // Check if the media query is true
  if (e.matches) {
    // Then log the following message to the console
    console.log('Media Query Matched!')
  }
}

isMobile.addListener(handleTabletChange)

What your code is doing:

const isMobile = window.matchMedia("only screen and (max-width: 830px)").matches

typeof isMobile
"boolean"

isMobile.matches
undefined

function handleTabletChange(e) {
  // Check if the media query is true
  if (e.matches) {
    // Then log the following message to the console
    console.log('Media Query Matched!')
  }
}

isMobile.addListner(handleTabletChange)

Uncaught TypeError: isMobile.addListner is not a function

Upvotes: 1

buzatto
buzatto

Reputation: 10382

Accordingly MediaQueryList matches method returns a boolean value.

you should only return your MediaQueryList to be able to addListener to it later:

const isMobile = window.matchMedia("only screen and (max-width: 830px)")

Upvotes: 1

Related Questions