Search code examples
reactjstypescriptreact-hookssidebar

Collapse React Sidebar using Hooks


I need to collapse my Sidebar base on screen size. So far I was not lucky with all my attempts. I was wondering if someone could give me some tips about that by using Hooks. The status is set to "isOpen={true}" and I need to make it false when reached width 768px or lower.

Thanks in advance

 return (
    <div className="menu-bar">
      <Menu
        width={210}
        isOpen={true}
        noOverlay
        noTransition
        pageWrapId={"page-wrap"}
        outerContainerId={"outer-container"}
        customBurgerIcon={false}
        customCrossIcon={false}
        disableAutoFocus
        disableCloseOnEsc
      >

Solution

  • This custom hook uses Window.matchMedia() to return a Boolean according to the query passed:

    const { useMemo, useState, useEffect } = React
    
    const useMediaQuery = query => {
      const mql = useMemo(() => window.matchMedia(query))
    
      const [match, setMatch] = useState(mql.matches)
    
      useEffect(() => {
        const handler = e => setMatch(e.matches)
        mql.addListener(handler)
        
        return () => {
          mql.removeListener(handler)
        }
      }, [mql])
      
      return match
    }
    
    const Demo = () => {
      const close = useMediaQuery('(max-width: 600px)')
      
      return (
        <div className="container">
          {close || <aside />}
          <main />
        </div>
      )
    }
    
    ReactDOM.render(
      <Demo />,
      root
    )
    .container {
      display: flex;
      height: 75vh;
    }
    
    main {
      flex: 4;
      height: 100%;
      background: purple;
    }
    
    aside {
      flex: 1;
      height: 100%;
      background: gold;
    }
    <script crossorigin src="https://unpkg.com/react@17/umd/react.development.js"></script>
    <script crossorigin src="https://unpkg.com/react-dom@17/umd/react-dom.development.js"></script>
    
    <div id="root"></div>