Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I use React's prop-types package to check for a specific type of element?

I'd like to use prop-types to check for specifically an img or svg element (at the top level). How would I use the library to do that check or to create a custom prop type to do so?

like image 559
Kyle Holmberg Avatar asked Oct 19 '25 12:10

Kyle Holmberg


1 Answers

You can use the type attribute of the JSX object to check what HTML element is being passed through.


Child component

class SomeComponent extends React.Component {
    render() {
        const { passedElement } = this.props;

        return (
            {passedElement}
        );
    }
}

SomeComponent.propTypes = {
    passedElement: PropTypes.shape({
        type: PropTypes.oneOf(['img', 'svg']),
    }),
};


Parent component

class App extends React.Component {
    render() {
        // Warning: Failed prop type: Invalid prop `passedElement.type` of value `div` supplied to `SomeComponent`, expected one of ["img","svg"].
        return <SomeComponent passedElement={<div></div>} />

        // No error, renders as expected
        return <SomeComponent passedElement={<img />} />
    }
}

like image 95
Tim Avatar answered Oct 21 '25 03:10

Tim



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!