0

I'm trying to conditionally render a component inside another component that uses react-draggable. If my return function returns a div, dragging works fine. If my function returns SomeComponent, dragging breaks completely. I've tried React.forwardRef and attaching the ref to nodeRef on Draggable, and on the ref inside the component, but that doesn't work. Is this maybe a limit of react-draggable?

const Master = () => {
  const nodeRef = useRef(null);

  const renderComponent = (type) => {
    switch (type) {
      case "typography":
        // If we return <Typography />, drag stops working.
        // return <Typography content="Hello!" ref={nodeRef} />; // Not Working
        return <div ref={nodeRef}>hello</div>; // Working
      case "button":
        return <button>Click Me</button>;
      default:
        break;
    }
  };
  return (
    <Draggable nodeRef={nodeRef}>{renderComponent("typography")}</Draggable>
  );
};
const Typography = React.forwardRef(({ content }, ref) => {
  return <div ref={ref}>{content}</div>;
});

Here is a link to a forked codesandbox if you want to check it out. https://codesandbox.io/s/gallant-voice-ly8jyj?file=/src/Master.js:113-673

Thanks everyone!

1 Answer 1

1

Wrapping the renderComponent call in a div seems to solve the issue:

const Master = () => {
  const nodeRef = useRef(null);

  const renderComponent = (type) => {
    switch (type) {
      case "typography":
        return <Typography content="Hello!" />;
      case "button":
        return <button>Click Me</button>;
      default:
        break;
    }
  };
  return (
    <Draggable nodeRef={nodeRef}>
      <div ref={nodeRef}>{renderComponent("typography")}</div>
    </Draggable>
  );
};

You also don't require forwardRef in this case

Sign up to request clarification or add additional context in comments.

1 Comment

lol now that seems so obvious. Thank you!

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.