material-uitooltipreact-props

Position a MUI tooltip inside a container so that it does not overflow outside of the container


enter image description here

For example— in this image when i hover on the button (click) on the left side, the tooltip is going out of the red bordered container.

same thing happens for the right side button.

i want to change the tooltip position dynamically so that it stays inside the container for both the cases.

p.s - new to stackoverflow. If anything is wrong please pardon.

thanks in advance.

<Tooltip
  title=“aaa”
  arrow
  placement=“bottom”
 >
<button> click </button>
</Tooltip>

this is code for the MUI tooltip.i tried to look for props that can help me with this but failed.


Solution

  • You can do this by accessing the PopperProps in the Tooltip component.

    The documentation for this is a little buried, but Tooltip has access to all MUI Popper component properties, which contain the popperOptions. Within the API properties definitions for the Popper component, MUI refers you to popper.js docs. These docs will then tell you how you can apply PopperProps to get different behaviors. Check out popper.js.org for further info.

    const boundingElement = useRef();
    [...]
    <div
      ref={boundingElement}
    >
      <Tooltip
        title="Tooltip Tooltip Tooltip Tooltip Tooltip"
        PopperProps={{
          popperOptions: {
            modifiers: [
              {
                 name: "preventOverflow",
                 options: {
                   boundary: boundingElement.current
                 }
              }
            ]
          }
        }}
      >
        <div>Tooltip Hover Div</div>
      </Tooltip>
    </div>
    

    Edit: Sep 2023

    It was pointed out that the ref would not populate on the initial render, causing the tooltip to go out of bounds until another render was performed. My approach to fixing this is to force an update after the first render using the forceUpdate method from the React docs. It appears to be working (CodeSandbox). If anyone has a better way of defining a ref on a first render, please edit.

    const boundingElement = useRef();
    const [, forceUpdate] = useReducer(x => x + 1, 0);
      
    useLayoutEffect(() => {
      forceUpdate()
    }, [])
    
    [...]
    
    <div
      ref={boundingElement}
    >
      <Tooltip
        title="Tooltip Tooltip Tooltip Tooltip Tooltip"
        PopperProps={{
          popperOptions: {
            modifiers: [
              {
                 name: "preventOverflow",
                 options: {
                   boundary: boundingElement.current
                 }
              }
            ]
          }
        }}
      >
        <div>Tooltip Hover Div</div>
      </Tooltip>
    </div>