daily pastebin goal
83%
SHARE
TWEET

Untitled

a guest May 17th, 2018 99 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. import * as React from 'react';
  2.  
  3. /**
  4.  * Decorator to form a HOC that acts like a react context consumer.
  5.  * Useful when you want context to be made available in an entire component and not just in render.
  6.  *
  7.  * Example:
  8.  * type MyContextProps = {foo: string};
  9.  * const MyContext = createContext<MyContextProps>({foo: 'bar'});
  10.  *
  11.  * @consume(MyContext.Consumer)
  12.  * class MyComponent extends React.Component<MyContextProps> {
  13.  *   componentDidMount () {
  14.  *     // Context is now available in the entire component
  15.  *     console.log(this.props.foo);
  16.  *   }
  17.  *
  18.  *   render () {
  19.  *     return <span>{this.props.foo}</span>;
  20.  *   }
  21.  * }
  22.  */
  23. export function consume<ContextProps> (Consumer: React.Consumer<ContextProps>) {
  24.   return function decorateConsume<T extends React.ComponentClass> (DecoratedComponent: T): T {
  25.     class DecoratedConsumer extends React.Component {
  26.       render () {
  27.         const {children, ...localProps} = this.props;
  28.         return (
  29.           <Consumer>
  30.             {(contextProps) => (
  31.               <DecoratedComponent {...contextProps} {...localProps}>
  32.                 {children}
  33.               </DecoratedComponent>
  34.             )}
  35.           </Consumer>
  36.         );
  37.       }
  38.     }
  39.  
  40.     (DecoratedConsumer as any).displayName = DecoratedComponent.displayName || DecoratedComponent.name;
  41.  
  42.     return DecoratedConsumer as T;
  43.   };
  44. }
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
 
Top