Skip to content

Commit

Permalink
[DirectionProvider] add an inline prop
Browse files Browse the repository at this point in the history
The inline prop changes the wrapping element to a `<span>` instead of a `<div>`.
This can be used when setting the direction context of inline elements, to avoid
inserting a block level element.
  • Loading branch information
yzimet committed Jan 10, 2018
1 parent 9b4b1ca commit 94d093c
Show file tree
Hide file tree
Showing 3 changed files with 21 additions and 4 deletions.
2 changes: 1 addition & 1 deletion README.md
Expand Up @@ -47,7 +47,7 @@ You should set the `direction` prop based on the language of the content being r

`DirectionProvider` components can also be nested, so that the direction can be overridden for certain branches of the React tree.

`DirectionProvider` will render its children inside of a `<div>` element with a `dir` attribute set to match the `direction` prop, for example: `<div dir="rtl">`. This maintains consistency when being rendered in a browser.
`DirectionProvider` will render its children inside of a `<div>` element with a `dir` attribute set to match the `direction` prop, for example: `<div dir="rtl">`. This maintains consistency when being rendered in a browser. To render inside of a `<span>` instead of a div, set the `inline` prop to `true`.

Usage example:

Expand Down
13 changes: 10 additions & 3 deletions src/DirectionProvider.jsx
Expand Up @@ -13,8 +13,13 @@ import { DIRECTIONS, CHANNEL } from './constants';
const propTypes = forbidExtraProps({
children: PropTypes.node.isRequired,
direction: directionPropType.isRequired,
inline: PropTypes.bool,
});

const defaultProps = {
inline: false,
};

const childContextTypes = {
[CHANNEL]: brcastShape,
};
Expand All @@ -40,14 +45,16 @@ export default class DirectionProvider extends React.Component {
}

render() {
const { children, direction } = this.props;
const { children, direction, inline } = this.props;
const Tag = inline ? 'span' : 'div';
return (
<div dir={direction}>
<Tag dir={direction}>
{React.Children.only(children)}
</div>
</Tag>
);
}
}

DirectionProvider.propTypes = propTypes;
DirectionProvider.defaultProps = defaultProps;
DirectionProvider.childContextTypes = childContextTypes;
10 changes: 10 additions & 0 deletions tests/DirectionProvider_test.jsx
Expand Up @@ -24,6 +24,16 @@ describe('<DirectionProvider>', () => {
const wrapper = shallow(
<DirectionProvider direction={direction}>{children}</DirectionProvider>,
);
expect(wrapper).to.have.type('div');
expect(wrapper).to.have.prop('dir', direction);
});

it('renders a wrapping span when the inline prop is true', () => {
const direction = DIRECTIONS.RTL;
const wrapper = shallow(
<DirectionProvider direction={direction} inline>{children}</DirectionProvider>,
);
expect(wrapper).to.have.type('span');
expect(wrapper).to.have.prop('dir', direction);
});

Expand Down

0 comments on commit 94d093c

Please sign in to comment.