Cypress: How to handle selectors with different names on mobile and desktop running on different viewports? - cypress

I am new to Cypress 12.3 and trying to find out the best possible way to run my automation on different viewports. My website in some places uses different css selector on mobile e.g. on Search of a product, Later on checkout.
I was writing the code below where depending on the viewport size being mobile or desktop it will execute those steps. However in this process I realised that some steps would be repetitive in both if and else when the css selectors are same on mobile and desktop.
Please can some one assists in what is the best way to write the tests?
import AllowCookies from "../pagesObjects/components/AllowCookies"
import Header from "../pagesObjects/components/Header"
import PLPPage from "../pagesObjects/pages/PLPPage"
import BasePage from "../pagesObjects/pages/BasePage"
const sizes = [BasePage.setiPhoneViewport(),BasePage.setAndriodViewport(), BasePage.setTabletViewport(), [1280, 768]]
describe('Add random product to bag', () => {
let testData
beforeEach(() => {
cy.fixture('general').then(function (data) {
testData = data
cy.visit(data.baseURL + data.urlHomePath)
})
AllowCookies.clickOnAllowAll()
})
sizes.forEach((size) => {
it(` Add random products ${size} `, () => {
cy.currencyPopup()
if (Cypress._.isArray(size)) {
cy.viewport(size[0], size[1])
} else {
cy.viewport(size)
}
if (size === testData.sizeiPhone || size === testData.sizeAndroid || size === testData.sizeiPad) {
Header.searchMobile(testData.validSearchTxt)
PLPPage.clickARandomProduct()
}
else {
Header.search(testData.validSearchTxt)
PLPPage.clickARandomProduct()
}
})
})
})

Try adding "metadata" to the BasePage return values
// BasePage
setiPhoneViewport() {
return {
device: 'iphone-6',
isMobile: 'mobile'
}
}
// Test
if (Cypress._.isArray(size)) {
cy.viewport(size[0], size[1])
} else {
cy.viewport(size.device)
}
const search = size.isMobile ? Header.searchMobile : Header.search;
search(testData.validSearchTxt)
PLPPage.clickARandomProduct()
If you have a "custom" size that happens to be mobile,
const sizes = [
BasePage.setiPhoneViewport(),
BasePage.setAndriodViewport(),
BasePage.setTabletViewport(),
[1280, 768],
[320, 250], // is mobile
]
then include it in the expression
// Test
function getSearchMethod(size) {
return
}
if (Cypress._.isArray(size)) {
cy.viewport(size[0], size[1])
} else {
cy.viewport(size.device)
}
const search = size.isMobile || (Cypress._.isArray(size) && size[0] < 350) ?
Header.searchMobile : Header.search;
search(testData.validSearchTxt)
PLPPage.clickARandomProduct()

Related

Shopify 2.0 Dawn - How to hide unavailable variants?

PROBLEM
Unavailable variant combinations are different from sold-out because customers don't understand it's the selects which make certain combinations 'not possible'.
Shopify's way of handling this is to display 'Unavailable' in the buy button. But customers think this means sold-out when in reality, they've chosen the wrong combination of variants...
The previous JS workarounds to remove unavailable or 'not possible' variants don't work in Shopify 2.0's new default/flagship theme, Dawn because the JS is different.
As far as I can tell, Dawn's variant JS was recently moved from /asstes/variants.js to line 497 in /assets/global.js.
SKILL
My CSS is decent but my JS is lame, I'm a designer sorry.
QUESTIONS
Based on user interaction with the first variant, how do you hide unavailable variants (not sold-out) in Shopify 2.0 Dawn?
How do you make one variant option set a checkbox instead of a radio button or radio?
What's the best way to add custom text as the first option in selects? e.g. 'Choose a size...' or 'Choose a color...' etc. Is it best to hard-code or use JS for this as well?
RESOURCES/EXAMPLES
Here's a pull request which grabs sold-out from the new Dawn JS but I don't understand how to adapt it for 'Unavailable' sorry (which is a different exception from sold-out): https://github.com/Shopify/dawn/pull/105
Here's an example of how to hide unavailable variants in the older Debut theme which doesn’t seem to work in the newer Dawn JS: https://www.youtube.com/watch?v=vspWDu_POYA
Here's a link to the JS gist referenced in that video: https://gist.github.com/jonathanmoore/c0e0e503aa732bf1c05b7a7be4230c61
And finally, here's the new code from Dawn at line 497 in /assets/global.js
class VariantSelects extends HTMLElement {
constructor() {
super();
this.addEventListener('change', this.onVariantChange);
}
onVariantChange() {
this.updateOptions();
this.updateMasterId();
this.toggleAddButton(true, '', false);
this.updatePickupAvailability();
if (!this.currentVariant) {
this.toggleAddButton(true, '', true);
this.setUnavailable();
} else {
this.updateMedia();
this.updateURL();
this.updateVariantInput();
this.renderProductInfo();
}
}
updateOptions() {
this.options = Array.from(this.querySelectorAll('select'), (select) => select.value);
}
updateMasterId() {
this.currentVariant = this.getVariantData().find((variant) => {
return !variant.options.map((option, index) => {
return this.options[index] === option;
}).includes(false);
});
}
updateMedia() {
if (!this.currentVariant || !this.currentVariant?.featured_media) return;
const newMedia = document.querySelector(
`[data-media-id="${this.dataset.section}-${this.currentVariant.featured_media.id}"]`
);
if (!newMedia) return;
const parent = newMedia.parentElement;
parent.prepend(newMedia);
window.setTimeout(() => { parent.scroll(0, 0) });
}
updateURL() {
if (!this.currentVariant) return;
window.history.replaceState({ }, '', `${this.dataset.url}?variant=${this.currentVariant.id}`);
}
updateVariantInput() {
const productForms = document.querySelectorAll(`#product-form-${this.dataset.section}, #product-form-installment`);
productForms.forEach((productForm) => {
const input = productForm.querySelector('input[name="id"]');
input.value = this.currentVariant.id;
input.dispatchEvent(new Event('change', { bubbles: true }));
});
}
updatePickupAvailability() {
const pickUpAvailability = document.querySelector('pickup-availability');
if (!pickUpAvailability) return;
if (this.currentVariant?.available) {
pickUpAvailability.fetchAvailability(this.currentVariant.id);
} else {
pickUpAvailability.removeAttribute('available');
pickUpAvailability.innerHTML = '';
}
}
renderProductInfo() {
fetch(`${this.dataset.url}?variant=${this.currentVariant.id}&section_id=${this.dataset.section}`)
.then((response) => response.text())
.then((responseText) => {
const id = `price-${this.dataset.section}`;
const html = new DOMParser().parseFromString(responseText, 'text/html')
const destination = document.getElementById(id);
const source = html.getElementById(id);
if (source && destination) destination.innerHTML = source.innerHTML;
document.getElementById(`price-${this.dataset.section}`)?.classList.remove('visibility-hidden');
this.toggleAddButton(!this.currentVariant.available, window.variantStrings.soldOut);
});
}
toggleAddButton(disable = true, text, modifyClass = true) {
const addButton = document.getElementById(`product-form-${this.dataset.section}`)?.querySelector('[name="add"]');
if (!addButton) return;
if (disable) {
addButton.setAttribute('disabled', true);
if (text) addButton.textContent = text;
} else {
addButton.removeAttribute('disabled');
addButton.textContent = window.variantStrings.addToCart;
}
if (!modifyClass) return;
}
setUnavailable() {
const addButton = document.getElementById(`product-form-${this.dataset.section}`)?.querySelector('[name="add"]');
if (!addButton) return;
addButton.textContent = window.variantStrings.unavailable;
document.getElementById(`price-${this.dataset.section}`)?.classList.add('visibility-hidden');
}
getVariantData() {
this.variantData = this.variantData || JSON.parse(this.querySelector('[type="application/json"]').textContent);
return this.variantData;
}
}
customElements.define('variant-selects', VariantSelects);
class VariantRadios extends VariantSelects {
constructor() {
super();
}
updateOptions() {
const fieldsets = Array.from(this.querySelectorAll('fieldset'));
this.options = fieldsets.map((fieldset) => {
return Array.from(fieldset.querySelectorAll('input')).find((radio) => radio.checked).value;
});
}
}
customElements.define('variant-radios', VariantRadios);
Any help or pointers in the right direction would be much appreciated. Cheers

SPFX webpart property pane

I am trying to append sharepoint lists in dropdown of spfx webpart property pane. but its not getting appended. please help out.
export default class ScrollTickerWebPart extends BaseClientSideWebPart<IScrollTickerWebPartProps> {
private dropdownOptions: IPropertyPaneDropdownOption[];
private listsFetched: boolean;
private fetchLists(url: string) : Promise<any> {
return this.context.spHttpClient.get(url, SPHttpClient.configurations.v1).then((response: SPHttpClientResponse) => {
if (response.ok) {
return response.json();
} else {
console.log("WARNING - failed to hit URL " + url + ". Error = " + response.statusText);
return null;
}
});
}
private fetchOptions(): Promise<IPropertyPaneDropdownOption[]> {
var url = "https://abc.sharepoint.com/teams/SharepointPOC" + "/_api/web/lists?$filter=Hidden eq false";
return this.fetchLists(url).then((response) => {
var options: Array<IPropertyPaneDropdownOption> = new Array<IPropertyPaneDropdownOption>();
response.value.map((list: IODataList) => {
console.log("Found list with title = " + list.Title);
options.push( { key: list.Id, text: list.Title });
});
return options;
});
}
Wherever you call fetchOptions, make sure to call this.context.propertyPane.refresh() after the promise resolves. This is needed to force a re-render of the property pane with the new dropdownOptions.
As an example (somewhere other than onPropertyPaneConfigurationStart is fine as well):
protected onPropertyPaneConfigurationStart(): void {
this.fetchOptions().then(options => {
this.dropdownOptions = options;
this.context.propertyPane.refresh();
});
}
This is assuming that your PropertyPaneDropdown is setup something like below, where this.dropdownOptions are initially undefined, and you are wanting to asynchronously load them with fetchOptions():
PropertyPaneDropdown('someProperty', {
// ...
options: this.dropdownOptions,
// ...
})
Web part properties – dynamically populate Dropdown options in SPFX
we populate the dropdown with the SharePoint lists in the current site. We do this with an async REST call to SharePoint
/* need some imports e.g.:
import { IODataList } from '#microsoft/sp-odata-types';
import { SPHttpClient, SPHttpClientConfigurations,
SPHttpClientConfiguration, SPHttpClientResponse, ODataVersion,
ISPHttpClientConfiguration } from '#microsoft/sp-http';
*/
private dropdownOptions: IPropertyPaneDropdownOption[];
private listsFetched: boolean;
// these methods are split out to go step-by-step, but you could refactor
and be more direct if you choose..
private fetchLists(url: string) : Promise<any> {
return this.context.spHttpClient.get(url,
SPHttpClient.configurations.v1).then((response: SPHttpClientResponse) => {
if (response.ok) {
return response.json();
} else {
console.log("WARNING - failed to hit URL " + url + ". Error = " +
response.statusText);
return null;
}
});
}
private fetchOptions(): Promise<IPropertyPaneDropdownOption[]> {
var url = this.context.pageContext.web.absoluteUrl + `/_api/web/lists?
$filter=Hidden eq false`;
return this.fetchLists(url).then((response) => {
var options: Array<IPropertyPaneDropdownOption> = new
Array<IPropertyPaneDropdownOption>();
response.value.map((list: IODataList) => {
console.log("Found list with title = " + list.Title);
options.push( { key: list.Id, text: list.Title });
});
return options;
});
}
Then in the getPropertyPaneConfiguration method, we kick-off the call to fetch the data at the beginning, and then in the control declaration we simply set the options property to our variable holding the array:
protected getPropertyPaneConfiguration(): IPropertyPaneConfiguration {
if (!this.listsFetched) {
this.fetchOptions().then((response) => {
this.dropdownOptions = response;
this.listsFetched = true;
// now refresh the property pane, now that the promise has been
resolved..
this.onDispose();
});
}
return {
pages: [
{
header: {
description: "Basic settings"
},
groups: [
{
groupName: "COB dropdown field (PropertyPaneDropdown)",
groupFields: [
PropertyPaneDropdown('dropdownProperty', {
label: 'This is the label',
options: this.dropdownOptions
})
]
}
]
}
]
}
}
Refer this Web part properties – dynamically populate Dropdown
You can use PropertyFieldListPicker control which is really easy to use.
This control generates a list picker field that can be used in the property pane of your SharePoint Framework web parts.
The control can be configured as a single or multi-selection list picker. Please check the below link :
https://sharepoint.github.io/sp-dev-fx-property-controls/controls/PropertyFieldListPicker/
You can use PNP PropertyFieldListPicker,
https://pnp.github.io/sp-dev-fx-property-controls/controls/PropertyFieldListPicker/

How To Split Mobx State Tree Models Across Multiple Files?

I have a Mobx State Tree model that has grown too long and I would like to split it across multiple javascript files.
Here is a demo of some of the code:
///file1.js
import { types } from "mobx-state-tree";
export const ExampleModel = types
.model("Example", {
id: types.identifier,
name: types.optional(types.string, ""),
anotherName: types.optional(types.string, ""),
})
.views(self => ({
get test() {
return "test"
}
}))
.views(self => ({
get anotherTest() {
return "anotherTest"
}
}))
.actions(self => ({
setName(name) {
self.name = name
}
}))
.actions(self => ({
setAnotherName(name) {
self.anotherName = name
}
}))
What I want is to split this between two files, like:
///file1.js
import { types } from "mobx-state-tree";
export const ExampleModel = types
.model("Example", {
id: types.identifier,
name: types.optional(types.string, ""),
anotherName: types.optional(types.string, ""),
})
.views(self => ({
get test() {
return "test"
}
}))
.actions(self => ({
setName(name) {
self.name = name
}
}))
///file2.js
import { ExampleModel } from "./file1.js";
ExampleModel.views(self => ({
get anotherTest() {
return "anotherTest"
}
})).actions(self => ({
setAnotherName(name) {
self.anotherName = name
}
}))
You can see here that I am attempting to move a view and and action to a separate javascript file. I expect I need to do some kind of import and export between these two files, but I can't figure out how to do it.
I know that Mobx State Tree has compose functionality, as shown here:
https://nathanbirrell.me/notes/composition-mobx-state-tree/
But I am afer something more simple than this... I don't want to set up multiple models, I just need the ability to spread a model across multiple javascript files.
We do that all the time.
Just export your actions and views separately:
// file1.js
import { types } from "mobx-state-tree"
export const props = {
id: types.identifier,
name: types.optional(types.string, ""),
anotherName: types.optional(types.string, ""),
}
export const views = self => ({
get test() {
return "test"
}
})
export const actions = self => ({
setName(name) {
self.name = name
}
})
Then, create the final store from them:
// store.js
import { types } from "mobx-state-tree"
import * as file1 from "./file1"
import * as file2 from "./file2"
const Store = types
.model('Store')
.props(file1.props)
.views(file1.views)
.actions(file1.actions)
.props(file2.props)
.views(file2.views)
.actions(file2.actions)
export default Store
You can also create your own stores for testing, only from one file:
// __tests__/file1.js
import { types } from "mobx-state-tree"
import { actions, views, props } from "./file1"
const Store = types
.model('Store')
.props(props)
.views(views)
.actions(actions)
const store = Store.create(myTestSnapshot)
test('setName should set the name prop', () => {
store.setName('john')
expect(store.name).toBe('john')
})
Expressive, flexible and easy model composition is one of the best features in mobx-state-tree! :)
Here are two examples, taken straight from the relevant section in the docs:
const Square = types
.model("Square", {
width: types.number
})
.views(self => ({
surface() {
return self.width * self.width
}
}))
// create a new type, based on Square
const Box = Square
.named("Box")
.views(self => {
// save the base implementation of surface
const superSurface = self.surface
return {
// super contrived override example!
surface() {
return superSurface() * 1
},
volume() {
return self.surface * self.width
}
}
}))
// no inheritance, but, union types and code reuse
const Shape = types.union(Box, Square)
And another one:
const CreationLogger = types.model().actions(self => ({
afterCreate() {
console.log("Instantiated " + getType(self).name)
}
}))
const BaseSquare = types
.model({
width: types.number
})
.views(self => ({
surface() {
return self.width * self.width
}
}))
export const LoggingSquare = types
.compose(
// combine a simple square model...
BaseSquare,
// ... with the logger type
CreationLogger
)
// ..and give it a nice name
.named("LoggingSquare")
Applying that to your needs: Square and Box can be in different files, where Box.js imports Square from Square.js in the first example.
Same exact technique can be applied to the second example.

dropdown list with an extend option

I'm using the DropdownList component from react-widget. In my code, there are a couple of dropdowns that get their values from an Ajax call. Some of them, like a list of languages, are too big and it's very slow to get the list from Ajax and render it (takes 4 to 5 seconds!). I would like to provide to the dropdwon a small list of languages and an 'Extend' or 'Load Full List' option; if clicking on Extend the dropdown would be refreshed with the full list of languages.
Here is my solution: the code of the parent component:
const languages = ajaxCalls.getLanguages();
const langs = {"languages": [["eng", "English"], ["swe", "Swedish"], ["deu", "German"], ["...", "Load Full List"]]};
const common_langs = langs.languages.map(([id, name]) => ({id, name}));
<SelectBig data={common_langs} extend={languages} onSelect={x=>this.setValue(schema, path, x)} value={this.getValue(path)} />;
And here is the code for SelectBig component:
import React from 'react/lib/ReactWithAddons';
import { DropdownList } from 'react-widgets';
const PT = React.PropTypes;
export const SelectBig = React.createClass({
propTypes: {
data: PT.array,
value: PT.string,
onSelect: PT.func.isRequired,
},
maxResults: 50,
shouldComponentUpdate(nextProps, nextState) {
console.log("nextProps = " , nextProps, " , nextState = ", nextState);
const len = x => (x && x.length !== undefined) ? x.length : 0;
// fast check, not exact, but should work for our use case
return nextProps.value !== this.props.value
|| len(nextProps.data) !== len(this.props.data);
},
getInitialState(){
return {
lastSearch: '',
results: 0,
dataList: [],
};
},
select(val) {
if(val.id === "..."){
this.setState({dataList: this.props.extend})
}
this.props.onSelect(val.id);
},
filter(item, search) { .... },
renderField(item) { .... },
render() {
const busy = !this.props.data;
let data;
if(!this.props.extend){
data = this.props.data || [];
} else {
data = this.state.dataList;
}
return (
<DropdownList
data={data}
valueField='id'
textField={this.renderField}
value={this.props.value}
onChange={this.select}
filter={this.filter}
caseSensitive={false}
minLength={2}
busy={busy} />
);
}
});
But it doesn't look good: When the user chooses 'Load Full List', the dropdown list will be closed and user need to click again to see the updated list. Does anyone have a better solution or a suggestion to improve my code?
The picture shows how it looks like right now!
https://www.npmjs.com/package/react-select-2
Better go with this link, it will work

only allow children of a specific type in a react component

I have a Card component and a CardGroup component, and I'd like to throw an error when CardGroup has children that aren't Card components. Is this possible, or am I trying to solve the wrong problem?
For React 0.14+ and using ES6 classes, the solution will look like:
class CardGroup extends Component {
render() {
return (
<div>{this.props.children}</div>
)
}
}
CardGroup.propTypes = {
children: function (props, propName, componentName) {
const prop = props[propName]
let error = null
React.Children.forEach(prop, function (child) {
if (child.type !== Card) {
error = new Error('`' + componentName + '` children should be of type `Card`.');
}
})
return error
}
}
You can use the displayName for each child, accessed via type:
for (child in this.props.children){
if (this.props.children[child].type.displayName != 'Card'){
console.log("Warning CardGroup has children that aren't Card components");
}
}
You can use a custom propType function to validate children, since children are just props. I also wrote an article on this, if you want more details.
var CardGroup = React.createClass({
propTypes: {
children: function (props, propName, componentName) {
var error;
var prop = props[propName];
React.Children.forEach(prop, function (child) {
if (child.type.displayName !== 'Card') {
error = new Error(
'`' + componentName + '` only accepts children of type `Card`.'
);
}
});
return error;
}
},
render: function () {
return (
<div>{this.props.children}</div>
);
}
});
For those using a TypeScript version.
You can filter/modify components like this:
this.modifiedChildren = React.Children.map(children, child => {
if (React.isValidElement(child) && (child as React.ReactElement<any>).type === Card) {
let modifiedChild = child as React.ReactElement<any>;
// Modifying here
return modifiedChild;
}
// Returning other components / string.
// Delete next line in case you dont need them.
return child;
});
Use the React.Children.forEach method to iterate over the children and use the name property to check the type:
React.Children.forEach(this.props.children, (child) => {
if (child.type.name !== Card.name) {
console.error("Only card components allowed as children.");
}
}
I recommend to use Card.name instead of 'Card' string for better maintenance and stability in respect to uglify.
See: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/name
One has to use "React.isValidElement(child)" along with "child.type" if one is working with Typescript in order to avoid type mismatch errors.
React.Children.forEach(props.children, (child, index) => {
if (React.isValidElement(child) && child.type !== Card) {
error = new Error(
'`' + componentName + '` only accepts children of type `Card`.'
);
}
});
You can add a prop to your Card component and then check for this prop in your CardGroup component. This is the safest way to achieve this in React.
This prop can be added as a defaultProp so it's always there.
class Card extends Component {
static defaultProps = {
isCard: true,
}
render() {
return (
<div>A Card</div>
)
}
}
class CardGroup extends Component {
render() {
for (child in this.props.children) {
if (!this.props.children[child].props.isCard){
console.error("Warning CardGroup has a child which isn't a Card component");
}
}
return (
<div>{this.props.children}</div>
)
}
}
Checking for whether the Card component is indeed a Card component by using type or displayName is not safe as it may not work during production use as indicated here: https://github.com/facebook/react/issues/6167#issuecomment-191243709
I made a custom PropType for this that I call equalTo. You can use it like this...
class MyChildComponent extends React.Component { ... }
class MyParentComponent extends React.Component {
static propTypes = {
children: PropTypes.arrayOf(PropTypes.equalTo(MyChildComponent))
}
}
Now, MyParentComponent only accepts children that are MyChildComponent. You can check for html elements like this...
PropTypes.equalTo('h1')
PropTypes.equalTo('div')
PropTypes.equalTo('img')
...
Here is the implementation...
React.PropTypes.equalTo = function (component) {
return function validate(propValue, key, componentName, location, propFullName) {
const prop = propValue[key]
if (prop.type !== component) {
return new Error(
'Invalid prop `' + propFullName + '` supplied to' +
' `' + componentName + '`. Validation failed.'
);
}
};
}
You could easily extend this to accept one of many possible types. Maybe something like...
React.PropTypes.equalToOneOf = function (arrayOfAcceptedComponents) {
...
}
static propTypes = {
children : (props, propName, componentName) => {
const prop = props[propName];
return React.Children
.toArray(prop)
.find(child => child.type !== Card) && new Error(`${componentName} only accepts "<Card />" elements`);
},
}
I published the package that allows to validate the types of React elements https://www.npmjs.com/package/react-element-proptypes :
const ElementPropTypes = require('react-element-proptypes');
const Modal = ({ header, items }) => (
<div>
<div>{header}</div>
<div>{items}</div>
</div>
);
Modal.propTypes = {
header: ElementPropTypes.elementOfType(Header).isRequired,
items: React.PropTypes.arrayOf(ElementPropTypes.elementOfType(Item))
};
// render Modal
React.render(
<Modal
header={<Header title="This is modal" />}
items={[
<Item/>,
<Item/>,
<Item/>
]}
/>,
rootElement
);
To validate correct children component i combine the use of react children foreach and the Custom validation proptypes, so at the end you can have the following:
HouseComponent.propTypes = {
children: PropTypes.oneOfType([(props, propName, componentName) => {
let error = null;
const validInputs = [
'Mother',
'Girlfried',
'Friends',
'Dogs'
];
// Validate the valid inputs components allowed.
React.Children.forEach(props[propName], (child) => {
if (!validInputs.includes(child.type.name)) {
error = new Error(componentName.concat(
' children should be one of the type:'
.concat(validInputs.toString())
));
}
});
return error;
}]).isRequired
};
As you can see is having and array with the name of the correct type.
On the other hand there is also a function called componentWithName from the airbnb/prop-types library that helps to have the same result.
Here you can see more details
HouseComponent.propTypes = {
children: PropTypes.oneOfType([
componentWithName('SegmentedControl'),
componentWithName('FormText'),
componentWithName('FormTextarea'),
componentWithName('FormSelect')
]).isRequired
};
Hope this help some one :)
Considered multiple proposed approaches, but they all turned out to be either unreliable or overcomplicated to serve as a boilerplate. Settled on the following implementation.
class Card extends Component {
// ...
}
class CardGroup extends Component {
static propTypes = {
children: PropTypes.arrayOf(
(propValue, key, componentName) => (propValue[key].type !== Card)
? new Error(`${componentName} only accepts children of type ${Card.name}.`)
: null
)
}
// ...
}
Here're the key ideas:
Utilize the built-in PropTypes.arrayOf() instead of looping over children
Check the child type via propValue[key].type !== Card in a custom validator
Use variable substitution ${Card.name} to not hard-code the type name
Library react-element-proptypes implements this in ElementPropTypes.elementOfType():
import ElementPropTypes from "react-element-proptypes";
class CardGroup extends Component {
static propTypes = {
children: PropTypes.arrayOf(ElementPropTypes.elementOfType(Card))
}
// ...
}
An easy, production friendly check. At the top of your CardGroup component:
const cardType = (<Card />).type;
Then, when iterating over the children:
React.children.map(child => child.type === cardType ? child : null);
The nice thing about this check is that it will also work with library components/sub-components that don't expose the necessary classes to make an instanceof check work.
Assert the type:
props.children.forEach(child =>
console.assert(
child.type.name == "CanvasItem",
"CanvasScroll can only have CanvasItem component as children."
)
)
Related to this post, I figured out a similar problem I had. I needed to throw an error if a child was one of many icons in a Tooltip component.
// icons/index.ts
export {default as AddIcon} from './AddIcon';
export {default as SubIcon} from './SubIcon';
...
// components/Tooltip.tsx
import { Children, cloneElement, isValidElement } from 'react';
import * as AllIcons from 'common/icons';
...
const Tooltip = ({children, ...rest}) => {
Children.forEach(children, child => {
// ** Inspired from this post
const reactNodeIsOfIconType = (node, allIcons) => {
const iconTypes = Object.values(allIcons);
return iconTypes.some(type => typeof node === 'object' && node !== null && node.type === type);
};
console.assert(!reactNodeIsOfIconType(child, AllIcons),'Use some other component instead...')
})
...
return Children.map(children, child => {
if (isValidElement(child) {
return cloneElement(child, ...rest);
}
return null;
});
}

Resources