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?
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 />} />
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With