Home > other >  How can i change a state in react when I change the size of website?
How can i change a state in react when I change the size of website?

Time:05-16

Here is the state :

const [open, setOpen] = useState(false);

The state is being controlled by an onclick event on icon which looks like :

onclick=()=>{setOpen(!open)}

I want to set the state setOpen(false) when it is in the larger window . Now how Can I implement this on my code ?

CodePudding user response:

Try this :

import React, { useLayoutEffect, useState } from 'react';

function useWindowSize() {
  const [size, setSize] = useState([0, 0]);
  useLayoutEffect(() => {
    function updateSize() {
      setSize([window.innerWidth, window.innerHeight]);
    }
    window.addEventListener('resize', updateSize);
    updateSize();
    return () => window.removeEventListener('resize', updateSize);
  }, []);
  return size;
}

CodePudding user response:

You can do this by using a media query. By using a media query, rather than listening for any resize event, you can look out for only certain breakpoints (lg, md, sm, etc.).

All-in-one external library:

useMediaQuery from MUI is easy to use and reliable. Below is a simple example that is watching for 600px screen size.

import * as React from 'react'
import useMediaQuery from '@mui/material/useMediaQuery'

export default function SimpleMediaQuery()
{
  const matches = useMediaQuery('(min-width:600px)')

  return <span>{`(min-width:600px) matches: ${matches}`}</span>
}

Want to use the preset breakpoints instead?

const matches = useMediaQuery(theme.breakpoints.up('sm'))

Callback?

const matches = useMediaQuery((theme) => theme.breakpoints.up('sm'))

This hook can be customized in multiple ways (see the docs linked above for more examples).


Custom hook with no external libraries:

If you want to do it without relying on an external library, here is a simple hook that watches for certain breakpoints, similar to MUI's useMediaQuery.

export const useMediaQuery = (width) =>
{
  const [targetReached, setTargetReached] = useState(false)

  const updateTarget = useCallback((e) =>
  {
    if (e.matches) setTargetReached(true)
    else setTargetReached(false)
  }, [])

  useEffect(() =>
  {
    const media = window.matchMedia(`(max-width: ${width}px)`)
    media.addEventListener('change', updateTarget)

    // Check on mount (callback is not called until a change occurs)
    if (media.matches) setTargetReached(true)

    return () => media.removeEventListener('change', updateTarget)
  }, [])

  return targetReached
}

Usage:

// 600px
const matches = useMediaQuery(600)
  • Related