Permalink
0c144c4 Feb 6, 2018
1 contributor

Users who have contributed to this file

94 lines (62 sloc) 2.01 KB

Context

Provides a generic way to safely use React's context. Re-renders consumer components when provider changes value.

Example

import {Provider, Context} from 'libreact/lib/context';

<Provider name="theme" value={{color: 'red'}}>
  <Consumer name="theme">{(theme) => {
      return <div>Color is: {theme.color}</div>;
  }}</Consumer>
</Provider>

<Provider>

Uses React's context functionality to provide data to child nodes.

Props

Signature

interface IProviderProps {
  name: string;
  value: any;
}

, where

  • name - context channel name
  • value - value to be broadcasted in this channel.

<Consumer>

Retrieves context value from specified channel.

Props

  • name - provider channel to subscribe to.

withContext() HOC

HOC that ensures your component will receive context value it subscribed to.

withContext: (Comp: React.Component, propName?: string, props?: IProviderProps) => React.Component;

, where

  • Comp — your React component.
  • propName — prop that will hold context value.
  • props — props passed to <Consumer>.

Returns a connected component that will have a prop named propName with value fetched from context.

If propName is not specified or set as an empty string, the context value will be merged into component's props.

Example

import {withContext} from 'libreact/lib/context';

const ColorIs = ({theme}) => <div>Color is: {theme.color}</div>;
const ColorIsConnected = withContext(ColorIs, 'theme', {name: 'theme'});

<Provider name="theme" value={{color: 'tomato'}}>
  <ColorIsConnected />
</Provider>

@withContext Decorator

Similar to withContenxt() but a decorators that injects context value into stateful component's props.

import {withContext} from 'libreact/lib/context';

@withContext('theme', {name: 'theme'})
class App extends Component {
  render () {
    return <div style={{color: this.props.theme.color}}>foo</div>;
  }
}