Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[NO JIRA] add 'hasChildrenOfType' to bpk-react-utils #407

Closed
wants to merge 1 commit into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
3 changes: 3 additions & 0 deletions changelog.md
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,9 @@
## UNRELEASED

_Nothing yet..._
**Added**:
- bpk-react-utils:
- Added 'hasChildrenOfType' prop type checker

## 2017-12-21 - Fix web button warnings

Expand Down
3 changes: 3 additions & 0 deletions packages/bpk-react-utils/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -21,18 +21,21 @@ import Portal from './src/Portal';
import cssModules from './src/cssModules';
import TransitionInitialMount from './src/TransitionInitialMount';
import withDefaultProps from './src/withDefaultProps';
import hasChildrenOfType from './src/hasChildrenOfType';

export {
Portal,
cssModules,
TransitionInitialMount,
withDefaultProps,
wrapDisplayName,
hasChildrenOfType,
};
export default {
Portal,
cssModules,
TransitionInitialMount,
withDefaultProps,
wrapDisplayName,
hasChildrenOfType,
};
45 changes: 45 additions & 0 deletions packages/bpk-react-utils/readme.md
Original file line number Diff line number Diff line change
Expand Up @@ -164,3 +164,48 @@ const MyComponent = (props) => (
| appearClassName | string | true | - |
| appearActiveClassName | string | true | - |
| transitionTimeout | number | true | - |

## hasChildrenOfType.js

A prop type checker that allows you to restrict a component's children to a specific type.
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Can we explain how this is different to PropTypes.instanceOf? That was my first question upon seeing this.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Would adding 'Component' help? Totally open to suggestions if you have any ideas.
eg.

A prop type checker that allows you to restrict a component's children to a specific (Component) type.

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@janeklb I second @k0nserv's question, what's the difference between using hasChildrenOfType(MyComponent) & PropTypes.instanceOf(MyComponent)? I.e. i think we are questioning whether this new prop type is redundant or not.

Copy link
Contributor Author

@janeklb janeklb Jan 2, 2018

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

PropTypes.instanceOf(...) uses js's instanceof operator to see if the prop value is an instance of the supplied class/type. It doesn't work with components (ie. jsx or React.createElement etc.) since those can't be operated on with instanceof.

This type checker validates that the children of a component are all "instances" of a certain component.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

See the tests - they should give some more clarity :)

Copy link
Contributor Author

@janeklb janeklb Jan 2, 2018

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

tbh im not sure why this isn't a part of prop-types itself -- seems like a common enough requirement

update: looks like it may be soon.. facebook/prop-types#146

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

And airbnb's prop types seem to already support something like this https://www.npmjs.com/package/airbnb-prop-types


### Usage

```js
import React from 'react';
import { hasChildrenOfType } from 'bpk-react-utils';

const Child = () => <span>Child</span>;

const Parent = ({ children }) => <div>{ children }</div>;
Parent.propTypes = {
children: hasChildrenOfType(Child),
};

// Valid:
const WithValidChildren = () => (
<Parent>
<Child />
<Child />
</Parent>
);

// Invalid (will get prop type validation errors):
const WithInvalidChildren = () => (
<Parent>
<Child />
<div>something else</div>
</Parent>
);
```

### Parameters

```js
function hasChildrenOfType(Type, atLeast = 1)
```

| Parameter | Description | Required | Default Value |
| ---------- | ------------------------------- | -------- | ------------- |
| `Type` | The component type to check for | true | - |
| `atLeast` | The mimumum number of children | false | 1 |
103 changes: 103 additions & 0 deletions packages/bpk-react-utils/src/hasChildrenOfType-test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,103 @@
/*
* Backpack - Skyscanner's Design System
*
* Copyright 2017 Skyscanner Ltd
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

import React from 'react';
import getDisplayName from 'recompose/getDisplayName';
import hasChildrenOfType from './hasChildrenOfType';

const Component = () => <div>Component</div>;
const Child = () => <span>Child</span>;

const runPropTypeValidatorWith = (
component,
{ atLeast = 1, propName = 'children', type = Child } = {},
) => {
const propTypeValidator = hasChildrenOfType(type, atLeast);
return propTypeValidator(
component.props,
propName,
getDisplayName(component.type),
);
};

describe('hasChildrenOfType', () => {
it('should not return an error if conditions are satisfied', () => {
const error = runPropTypeValidatorWith(
<Component>
<Child />
</Component>,
);
expect(error).toBeUndefined();
});

it('should return an error if it has less children than it should (0 < 1)', () => {
const error = runPropTypeValidatorWith(<Component />);
expect(error).toEqual(
Error("Component requires at least 1 'Child' child."),
);
});

it('should return an error if it has less children than it should (1 < 2)', () => {
const error = runPropTypeValidatorWith(
<Component>
<Child />
</Component>,
{ atLeast: 2 },
);
expect(error).toEqual(
Error("Component requires at least 2 'Child' children."),
);
});

it('should not return an error if it does not require children', () => {
const error = runPropTypeValidatorWith(<Component />, { atLeast: 0 });
expect(error).toBeUndefined();
});

it('should return an error if it has single non matching child ', () => {
const error = runPropTypeValidatorWith(
<Component>
<div />
</Component>,
);
expect(error).toEqual(
Error("Component only allows 'Child' as children. Found 'div'."),
);
});

it('should return an error if it has a mix of matching and non matching children ', () => {
const error = runPropTypeValidatorWith(
<Component>
<Child />
<div />
</Component>,
);
expect(error).toEqual(
Error("Component only allows 'Child' as children. Found 'div'."),
);
});

it(`should return an error if used on a prop other than 'children'`, () => {
const error = runPropTypeValidatorWith(<Component something={Child} />, {
propName: 'something',
});
expect(error).toEqual(
Error(`hasChildrenOfType can only be used on 'children' propTypes`),
);
});
});
54 changes: 54 additions & 0 deletions packages/bpk-react-utils/src/hasChildrenOfType.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
/*
* Backpack - Skyscanner's Design System
*
* Copyright 2017 Skyscanner Ltd
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

import { Children } from 'react';
import getDisplayName from 'recompose/getDisplayName';

const hasChildrenOfType = (type, atLeast = 1) => (
props,
propType,
componentName,
) => {
if (propType !== 'children') {
return Error(`hasChildrenOfType can only be used on 'children' propTypes`);
}

if (Children.count(props[propType]) < atLeast) {
const inflectedNoun = atLeast === 1 ? 'child' : 'children';
return Error(
`${componentName} requires at least ${atLeast} '${getDisplayName(
type,
)}' ${inflectedNoun}.`,
);
}

const children = Children.toArray(props[propType]);
for (let i = 0; i < children.length; i += 1) {
const child = children[i];
if (child.type !== type && !(child.type.prototype instanceof type)) {
return Error(
`${componentName} only allows '${getDisplayName(type)}' as children. ` +
`Found '${getDisplayName(child.type)}'.`,
);
}
}

return undefined;
};

export default hasChildrenOfType;