14

I would like to have the material ui drawer's width resizable through a draggable handle. My current approach is to have a mousevent listener on the whole app which checks if handle was pressed and updates the width according to mouse position on every mouse move.

This however requires a constant mouseevent listener on the whole app which seems to be overkill for a simple resize feature.

Are there better/ recommended ways of doing the resize?

5 Answers 5

21
+100

You can use indicator dragger with mousedown on it.

Here for example

// styles
dragger: {
  width: '5px',
  cursor: 'ew-resize',
  padding: '4px 0 0',
  borderTop: '1px solid #ddd',
  position: 'absolute',
  top: 0,
  left: 0,
  bottom: 0,
  zIndex: '100',
  backgroundColor: '#f4f7f9'
}

...

state = {
  isResizing: false,
  lastDownX: 0,
  newWidth: {}
};

handleMousedown = e => {
  this.setState({ isResizing: true, lastDownX: e.clientX });
};

handleMousemove = e => {
  // we don't want to do anything if we aren't resizing.
  if (!this.state.isResizing) {
    return;
  }

  let offsetRight =
    document.body.offsetWidth - (e.clientX - document.body.offsetLeft);
  let minWidth = 50;
  let maxWidth = 600;
  if (offsetRight > minWidth && offsetRight < maxWidth) {
    this.setState({ newWidth: { width: offsetRight } });
  }
};

handleMouseup = e => {
  this.setState({ isResizing: false });
};

componentDidMount() {
  document.addEventListener('mousemove', e => this.handleMousemove(e));
  document.addEventListener('mouseup', e => this.handleMouseup(e));
}

...

<Drawer
  variant="permanent"
  open
  anchor={'right'}
  classes={{
    paper: classes.drawerPaper
  }}
  PaperProps={{ style: this.state.newWidth }}
>
  <div
    id="dragger"
    onMouseDown={event => {
      this.handleMousedown(event);
    }}
    className={classes.dragger}
  />
  {drawer}
</Drawer>

The idea is, when click the dragger, it will resize width Drawer followed mouse move.

Play DEMO.

8
  • Thanks for this awesome reply! Before accepting this answer, what would you think about only adding the mousemove listener on click of drag handle and unregistering on mouseup? This would prevent the mousemove event listener to be on 99% of the time.
    – nauti
    Mar 29, 2018 at 17:11
  • @nauti, Do you mean by Drawer? if so, you can do it as long as Drawer has handle mousemove prop (I have not check it). If not you can put at children of Drawer. It depends on you how to implement this, I suggest you to think about UI/UX as well. Because mostly user will use it. like mouse will change to dragger icon when hover/click outside link (only link have pointer icon). It depend on your requirement. Mar 30, 2018 at 1:41
  • also you can add document.removeEventListener(...) to remove listener if you think need it at componentWillUnmount. Mar 30, 2018 at 1:43
  • When I click to resize, the container jumps and is about 10 px left of where my cursor is dragging. May 8, 2020 at 13:23
  • This is pretty cool! Thanks. May 2, 2022 at 13:31
10

It might be a useResize hook with API to enable resizing and providing current width.

import { useCallback, useEffect, useState } from 'react'

type UseResizeProps = {
  minWidth: number
}

type UseResizeReturn = {
  width: number
  enableResize: () => void
}

const useResize = ({
  minWidth,
}: UseResizeProps): UseResizeReturn => {
  const [isResizing, setIsResizing] = useState(false)
  const [width, setWidth] = useState(minWidth)

  const enableResize = useCallback(() => {
    setIsResizing(true)
  }, [setIsResizing])

  const disableResize = useCallback(() => {
    setIsResizing(false)
  }, [setIsResizing])

  const resize = useCallback(
    (e: MouseEvent) => {
      if (isResizing) {
        const newWidth = e.clientX // You may want to add some offset here from props
        if (newWidth >= minWidth) {
          setWidth(newWidth)
        }
      }
    },
    [minWidth, isResizing, setWidth],
  )

  useEffect(() => {
    document.addEventListener('mousemove', resize)
    document.addEventListener('mouseup', disableResize)

    return () => {
      document.removeEventListener('mousemove', resize)
      document.removeEventListener('mouseup', disableResize)
    }
  }, [disableResize, resize])

  return { width, enableResize }
}

export default useResize

Then you could decouple resizing logic from your layout component like this:

const Layout = () => {
  const { width, enableResize } = useResize({ minWidth: 200 });

  return (
    <Drawer
      variant="permanent"
      open
      PaperProps={{ style: { width } }}
    >
      {drawer}
      <div
        style={{ 
          position: 'absolute',
          width: '2px',
          top: '0',
          right: '-1px',
          bottom: '0',
          cursor: 'col-resize'
        }}
        onMouseDown={enableResize}
      />
    </Drawer>
)
2
  • 2
    Great solution :)
    – TimDog
    Dec 7, 2021 at 12:55
  • I found it was helpful to add another state initialX and set that as e.clientX in enableResize. Then in resize() widthChange= e.clientX - initialX; and setInitialX(e.clientWidth); setWidth(oldWidth => oldWidth + widthChange)
    – sirclesam
    Mar 2 at 1:06
6

I would like to add an answer that is more up to date using React Hooks.

You can do it like this, then:

CSS:

sidebar-dragger: {
  width: '5px',
  cursor: 'ew-resize',
  padding: '4px 0 0',
  borderTop: '1px solid #ddd',
  position: 'absolute',
  top: 0,
  left: 0,
  bottom: 0,
  zIndex: '100',
  backgroundColor: '#f4f7f9'
}

React (using hooks with refs and states)

let isResizing = null;

function ResizeableSidebar (props) {
  const sidebarPanel = React.useRef('sidebarPanel');
  const cbHandleMouseMove = React.useCallback(handleMousemove, []);
  const cbHandleMouseUp = React.useCallback(handleMouseup, []);

  function handleMousedown (e) {
    e.stopPropagation();
    e.preventDefault();
    // we will only add listeners when needed, and remove them afterward
    document.addEventListener('mousemove', cbHandleMouseMove);
    document.addEventListener('mouseup', cbHandleMouseUp);
    isResizing = true;
  };

  function handleMousemove (e) {
    if (!isResizing) {
      return;
    }

    let offsetRight =
      document.body.offsetWidth - (e.clientX - document.body.offsetLeft);
    let minWidth = 50;
    if (offsetRight > minWidth) {
      let curSize = offsetRight - 60;
      // using a ref instead of state will be way faster
      sidebarPanel.current.style.width = curSize + 'px';
    }
  };

  function handleMouseup (e) {
    if (!isResizing) {
      return;
    }
    isResizing = false;
    document.removeEventListener('mousemove', cbHandleMouseMove);
    document.removeEventListener('mouseup', cbHandleMouseUp);
  };

  return <div className="sidebar-container">
    <div
      className="sidebar-dragger"
      onMouseDown={handleMousedown}
    />
    <div>
      Your stuff goes here
    </div>
  </div>;
}
2
2

Just use a synthetic event on your handle element. That way, you can avoid the messiness/performance costs of having a universal event listener. Something like the following:

render() {
     return (
       <div onMouseDown={this.yourResizeFunc}>
       </div>
  );
}
5
  • so you mean three events for mousedown up and over? The problem is that if I do that on the element to be resized, the mouseover stops being fired when moving out of the div which should be resized. For that reason those three vents need to be registered on the parent which unfortunately is the whole app.
    – nauti
    Mar 27, 2018 at 1:41
  • @nauti couldn't you just do it on the 'whole app' then but check to make sure the mouse is within the div you want to be resized? Either that or use the onMouseDown of the div and onMouseUp of the app?
    – JeremyF
    Mar 27, 2018 at 4:25
  • @JeremyF yes that is the solution I tried to give in the ticket, but I am looking for a better/ more performant solution which does not require a constant mousemove listener the whole time the user is on the app just for a simple resize of a div.
    – nauti
    Mar 27, 2018 at 5:53
  • Is this component always mounted? If so, I don't think there's a way around having an event listener constantly registered for the mouseDown event. If there are cases where it's unmounted, you could add the event listener in componentDidMount and remove it in componentWillUnmount. If however, the resizable component is always visible, your going to need a listener of some kind. Besides, if it is in fact always mounted, it's not exactly dragging down the perf of other pages within your app. You can always optimize when the app grows and the component isn't always mounted
    – john_mc
    Mar 27, 2018 at 6:07
  • @JohnMcGowan what about adding the mouseover listener at click of the resize drag button and unregistering on mouseup?
    – nauti
    Mar 27, 2018 at 17:07
2

You can do that with css only, if that fits your need. It's the simplest solution. Look mom, no javascript.

.resizable {
  height: 150px;
  width: 150px;
  border: 1px solid #333;
  resize: horizontal;
  overflow: auto;
}
<div class="resizable"></div>

Reference on MDN

2
  • Unfortunately because of my drawer is from the rigght you would need a direction rtl which screws up the layout of the content + the resize handle can only be styled very limited.
    – nauti
    Mar 28, 2018 at 17:25
  • This has nothing to do with the material ui drawer Feb 24, 2021 at 11:54

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.