1 year ago

#355090

test-img

Sasha

How can I require a ref for child component?

I'm trying to create a React component which accepts a children prop. In order to function properly, children must be able to take a ref. That works fine if they are built-in React components, but if I pass in any custom component (either my own or from a library), there's a risk that the component cannot take a ref, breaking functionality.

const MyComponent = ({ children }: { children: WhatShouldThisBe }) => {
  // Passing the child onto a component from a library that expects to be able to pass it a ref
  return (
    <WrapperWhichExpectsChildToHaveRef>
      {children}
    </WrapperWhichExpectsChildToHaveRef>
  );
}

// Works
<MyComponent><div>Hello</div></MyComponent>

// Doesn't work, and should throw a type error
const NoForwardedRef = () => <div>Hello</div>
<MyComponent><NoForwardedRef /><MyComponent>

Functional components in React by default cannot take refs, so I couldn't pass a functional component in as a child, and have it work. Ideally, I'd like to require on a type level that only children which can receive refs are allowed, so that this is immediately apparent when using a "bad" component.

Is there a way to declare that the children prop must take a ref? In other words, is there some sort of type that is, essentially, ReactComponentWhichTakesRef? Searched around for answers (including this one), but surprisingly haven't found anything that fits this scenario.

reactjs

typescript

react-forwardref

0 Answers

Your Answer

Accepted video resources