PropTypes of specific component?

By : mpen
Source: Stackoverflow.com
Question!

I've got this simple React component:

import {PropTypes} from 'react';
import Column from './Column';

export default function ColumnContainer({children}) {
    return (
        <div className="cr-column-container">{children}</div>
    );
}

let ColumnType = PropTypes.instanceOf(Column);

ColumnContainer.propTypes = {
    children: PropTypes.oneOfType([
        ColumnType,
        PropTypes.arrayOf(ColumnType),
    ]).isRequired,
};

Which I use like this:

render() {
    return (
        <ColumnContainer>
            <Column>
                *snip*
            </Column>
        </ColumnContainer>
    );
}

But it's failing prop-type validation:

Warning: Failed prop type: Invalid prop `children` supplied to `ColumnContainer`.
    in ColumnContainer (created by ExampleContainer)
    in ExampleContainer

Why is that? I've only used Columns inside of the ColumnContainer. Does PropTypes.instanceOf(Column) not work like I expect? How am I supposed to specify that ColumnContainer will only accept children of type Column?

By : mpen


Answers
Did some digging, came up with this helper function based on josephmartin09's solution:

export function childrenOf(...types) {
    let fieldType = PropTypes.shape({
        type: PropTypes.oneOf(types),
    });

    return PropTypes.oneOfType([
        fieldType,
        PropTypes.arrayOf(fieldType),
    ]);
}

Usage:

ColumnContainer.propTypes = {
    children: childrenOf(Column).isRequired,
};

It's not ideal because it doesn't support native DOM elements like 'div' and the error message is worthless, but it'll do for now.

By : mpen


This video can help you solving your question :)
By: admin