tpszhaoLW
tpszhaoLW

Reputation: 13

React Forward Ref not working as with Custom Compoent

I need to wrap my custom component in the Material UI Tooltip. I believe I'm using ForwardRefs properly, however the tooltip does not appear at all regardless of events (hover,click, etc)

const MyComp = ({ buttonRef }) => {
    return <button ref={buttonRef}>this does not work</button>;
};

const MyCompForwardRef = React.forwardRef((props, ref) => {
  return <MyComp {...props} buttonRef={ref} />;
});

const FancyButton = React.forwardRef((props, ref) => (
  <button ref={ref}>this also does not work</button>
));

const Page = () => (
  <div style={{ display: "flex", flexDirection: "column" }}>
    <div style={{ margin: "10px" }}>
    <Tooltip title="23456789">
      //not working
      <MyCompForwardRef />
    </Tooltip>
  </div>
  <div style={{ margin: "10px" }}>
  <Tooltip title="23456789">
    //not working
    <FancyButton />
  </Tooltip>
  </div>
  <div style={{ margin: "10px" }}>
    <Tooltip title="23456789">
      <button>this works</button>
    </Tooltip>
  </div>
</div>);

Here is the sandbox link https://codesandbox.io/s/material-ui-card-styling-example-forked-9tqod?file=/src/index.js:438-914

Upvotes: 1

Views: 10737

Answers (1)

Dennis Vash
Dennis Vash

Reputation: 53944

First you need to update all versions, especially MUI version.

Second, you need to pass the props too, so it will apply the Tooltip styles and events to the inner component.

Everything mentioned in MUI docs

const MyComp = ({ buttonRef, ...props }) => {
  return (
    <button {...props} ref={buttonRef}>
      work
    </button>
  );
};

const MyCompForwardRef = React.forwardRef((props, ref) => {
  return <MyComp {...props} buttonRef={ref} />;
});

const FancyButton = React.forwardRef((props, ref) => {
  return (
    <button {...props} ref={ref}>
      work
    </button>
  );
});

https://codesandbox.io/s/mui-forwardref-tooltip-issue-forked-8u5vm?file=/src/index.js

Upvotes: 3

Related Questions