Guest User

Untitled

a guest
Apr 23rd, 2018
84
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.27 KB | None | 0 0
  1. import * as React from 'react';
  2.  
  3. type SupplyRef = (ref: HTMLElement | null) => void;
  4. type GetRef = SupplyRef;
  5. type ChildrenGetRef = (getRef: SupplyRef) => React.ReactNode;
  6.  
  7. interface Props {
  8. children: ChildrenGetRef | React.ReactNode;
  9. getRef?: GetRef;
  10. }
  11.  
  12. const RefContext = (React as any).createContext();
  13.  
  14. export default class RefCollector extends React.Component<Props> {
  15. render() {
  16. if (typeof this.props.children !== 'function') {
  17. return this.props.getRef ? (
  18. <RefContext.Consumer>
  19. {(setRefFunc?: SupplyRef) => (
  20. <RefContext.Provider
  21. value={(ref: HTMLElement | null) => {
  22. this.props.getRef && this.props.getRef(ref);
  23. setRefFunc && setRefFunc(ref);
  24. }}
  25. >
  26. {this.props.children}
  27. </RefContext.Provider>
  28. )}
  29. </RefContext.Consumer>
  30. ) : (
  31. this.props.children
  32. );
  33. }
  34.  
  35. return (
  36. <RefContext.Consumer>
  37. {(setRefFunc?: SupplyRef) =>
  38. typeof this.props.children === 'function' &&
  39. this.props.children((ref: HTMLElement) => {
  40. setRefFunc && setRefFunc(ref);
  41. this.props.getRef && this.props.getRef(ref);
  42. })
  43. }
  44. </RefContext.Consumer>
  45. );
  46. }
  47. }
Add Comment
Please, Sign In to add comment