I know that refs are used to access DOM elements directly without altering the state. I read that it's not possible to give refs to function components because they don't have a state.
Refs cannot be attached to function components. Although, we can define refs and attach them to either DOM elements or class components. The bottom line is — function components do not have instances so you can’t reference them.
taken from: https://blog.logrocket.com/cleaning-up-the-dom-with-forwardref-in-react/
I still don't understand.
I am using the Tooltip
component from Ant Design (https://ant.design/components/tooltip/), the Button
component and a custom CircleButton
component.
Given the following JSX:
<Tooltip placement="left" title={"Lock slot"}>
<CircleButton onClick={() => execute(client.close)} icon={<LockOutlined />} disabled={loading} />
</Tooltip>
And my CircleButton component. Used like this, it will generate the warning.
const CircleButton = (props) => // gives the warning
<Button shape="circle" size="small" style={{ marginRight: "8px" }} {...props} />
Warning: Function components cannot be given refs. Attempts to access this ref will fail. Did you mean to use React.forwardRef()?
Note that everything works as expected despite the warning.
If I edit it as follows though, it will work fine, why?
const CircleButton = forwardRef((props, ref) => // doesn't give the warning
<div ref={ref}>
<Button shape="circle" size="small" style={{ marginRight: "8px" }} {...props} />
</div>)
Does the div
component have a state? I don't get it. Is the forwardRef
doing some magic and creating a state for the div element?
Why then if I pass the ref
to the Button
component it still gives the warning?
const CircleButton = forwardRef((props, ref) => // gives the warning
<Button ref={ref} shape="circle" size="small" style={{ marginRight: "8px" }} {...props} />)
If I pass the antd
Button
directly as a child, it works. But this is because I suppose that the antd button has a state hence it can have refs.
<Tooltip placement="left" title={"Lock slot"}> // doesn't give the warning
<Button shape="circle" size="small" style={{ marginRight: "8px" }} />
</Tooltip>
input
element which helped me to fully understand it: https://mcmap.net/q/591645/-why-does-custom-input-component-cause-quot-function-components-cannot-be-given-refs-quot-warning – Microwave