UNPKG

1.38 kBJSXView Raw
1// This component provides a string to React context that is consumed by the
2// withDirection higher-order component. We can use this to give access to
3// the current layout direction for components to use.
4
5import PropTypes from 'prop-types';
6import React from 'react';
7import { forbidExtraProps } from 'airbnb-prop-types';
8import brcast from 'brcast';
9import brcastShape from './proptypes/brcast';
10import directionPropType from './proptypes/direction';
11import { DIRECTIONS, CHANNEL } from './constants';
12
13const propTypes = forbidExtraProps({
14 children: PropTypes.node.isRequired,
15 direction: directionPropType.isRequired,
16});
17
18const childContextTypes = {
19 [CHANNEL]: brcastShape,
20};
21
22export { DIRECTIONS };
23
24export default class DirectionProvider extends React.Component {
25 constructor(props) {
26 super(props);
27 this.broadcast = brcast(props.direction);
28 }
29
30 getChildContext() {
31 return {
32 [CHANNEL]: this.broadcast,
33 };
34 }
35
36 componentWillReceiveProps(nextProps) {
37 if (this.props.direction !== nextProps.direction) {
38 this.broadcast.setState(nextProps.direction);
39 }
40 }
41
42 render() {
43 const { children, direction } = this.props;
44 return (
45 <div dir={direction}>
46 {React.Children.only(children)}
47 </div>
48 );
49 }
50}
51
52DirectionProvider.propTypes = propTypes;
53DirectionProvider.childContextTypes = childContextTypes;