Search code examples
reactjstypescriptreact-hooksref

how can put ref to props.children


I want wrapping module for multi use.

so, I make an ItemComponent

export const DragItem = (props: DragProps) => {
  const [{... }, fooRef] = useFoo({

  })

  return (
    props.children // how can i send fooRef to here??
  )
}

I should send ref to props.children Is it possible?


Solution

  • check this : https://codesandbox.io/s/gracious-williams-ywv9m You need to use React.cloneElement to attach/pass extra data to children

    export const DragItem = (props: DragProps) => {
      const [foo, fooRef] = React.useState({});
      var childrenWithRef = React.Children.map(props.children, function(child) {
        return React.cloneElement(child, { fooRef: fooRef });
      });
      return childrenWithRef;
    };