Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[Slot] Access ref from props else fallback to element.ref #2811

Closed
wants to merge 2 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
5 changes: 4 additions & 1 deletion packages/react/presence/src/Presence.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,10 @@ const Presence: React.FC<PresenceProps> = (props) => {
: React.Children.only(children)
) as React.ReactElement;

const ref = useComposedRefs(presence.ref, (child as any).ref);
// Accessing the ref from props, else fallback to element.ref
// https://github.com/facebook/react/pull/28348
const childrenRef = child.props.ref ?? (child as any).ref;
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It's fine to access child.ref conditionally. React only warns when accessing child.ref iff a ref prop is actually passed.

const ref = useComposedRefs(presence.ref, childrenRef);
const forceMount = typeof children === 'function';
return forceMount || presence.isPresent ? React.cloneElement(child, { ref }) : null;
};
Expand Down
5 changes: 4 additions & 1 deletion packages/react/slot/src/Slot.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -61,9 +61,12 @@ const SlotClone = React.forwardRef<any, SlotCloneProps>((props, forwardedRef) =>
const { children, ...slotProps } = props;

if (React.isValidElement(children)) {
// Accessing the ref from props, else fallback to element.ref
// https://github.com/facebook/react/pull/28348
const childrenRef = children.props.ref ?? (children as any).ref;
return React.cloneElement(children, {
...mergeProps(slotProps, children.props),
ref: forwardedRef ? composeRefs(forwardedRef, (children as any).ref) : (children as any).ref,
ref: forwardedRef ? composeRefs(forwardedRef, childrenRef) : childrenRef,
});
}

Expand Down