3
votes

I am trying to define my list of PropTypes for a class component. The component can accept either a regular DOM element or window as its prop value. Currently, I have:

class FooContainer extends Component {
    static propTypes = {
        container: PropTypes.oneOfType([
            PropTypes.element,
            PropTypes.instanceOf(Element),
        ]),
    };
    static defaultProps = {
        container: window,
    };
    constructor(props: any) {
        super(props);
    }
    render() {
        return (
            <div />
        );
    }
}

However, when the component defaults to using window as the container prop, the following error is thrown:

Warning: Failed prop type: Invalid prop `container` supplied to `FooContainer`.

As such, what is the valid PropType to use for property with value of window?

1
Maybe PropTypes.instanceof(Window)?Andrew Li
@AndrewLi, Window is undefined, if i try window instead, i get Failed prop type: Right-hand side of 'instanceof' is not callable. i guess window is not instanceable? or doesnt have the instanceof method.haxxxton
How about instanceOf(window.constructor)Andrew Li
@AndrewLi, there we go :D if you pop that in an answer ill accept ithaxxxton

1 Answers

4
votes

What you can do is use oneOfType and include an instance of the window object's constructor, Window:

PropTypes.instanceOf(window.constructor)

This will allow any Window instance as a prop value.