everweij / react-laag

Hooks to build things like tooltips, dropdown menu's and popovers in React
https://www.react-laag.com
MIT License
906 stars 44 forks source link

Function components cannot be given refs. Attempts to access this ref will fail. Did you mean to use React.forwardRef()? #41

Closed EgorPashko closed 4 years ago

EgorPashko commented 4 years ago

Hey guys, I have some problem when I try to test my ToggleLayer, I receive an error.

image

Can you provide some information about whether this is related to "react-laag" or not?

My test I am using @testing-library/react

describe('Tooltip content', () => {
    it('should render tooltip if a text is not empty', () => {
        const content = faker.random.word();

        const { getByText } = render(
            <WithTooltip text={faker.random.word()}>
                <div>{content}</div>
            </WithTooltip>,
        );

        fireEvent.mouseOver(getByText(content));
        expect(ToolTip).toBeCalled();
    });
});

My component

export const WithTooltip = (props: PropsWithChildren<{ text: string }>) => {
    const text = props.text;
    return (
         <ToggleLayer
            ResizeObserver={ResizeObserver}
            renderLayer={({ layerProps, isOpen }) =>
                isOpen && (
                <Styled.ToolTip
                    ref={layerProps.ref}
                    style={{
                        ...layerProps.style,
                    }}
                >
                    <Styled.Text>{text}</Styled.Text>
                </Styled.ToolTip>
            )
        }
        placement={{
            anchor: anchor.TOP_CENTER,
            autoAdjust: true,
            triggerOffset: 5,
        }}
    >
        {({ open, close, triggerRef }) => (
            <span ref={triggerRef} onMouseOver={open} onMouseLeave={close}>
                {props.children}
            </span>
        )}
    </ToggleLayer>
    );
};
everweij commented 4 years ago

Hi @EgorPashko, thanks for reporting this issue. At first sight, there seems to be nothing wrong with your code. What does Styled.Tooltip look like? Is is a function component? If so, did you wrap it in React.forwardRef() (and have you forwarded the ref onto a native dom-element?)

EgorPashko commented 4 years ago

@everweij Thank you for your quick response Styled.Tooltip is styled-component library, how did I find out they have a bug related to my issue. https://github.com/styled-components/styled-components/issues/1990. Now, my code looks like this image

I think an issue is closed