Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I include window as a valid prop with PropTypes?

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?

like image 311
haxxxton Avatar asked Feb 12 '26 12:02

haxxxton


1 Answers

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.

like image 102
Andrew Li Avatar answered Feb 14 '26 04:02

Andrew Li



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!