How do I mark a property as having to be a DOM element?
This page says that PropTypes.element
is actually a React element, so what's the equivalent for DOM element?
In React we can access the DOM element using Refs. Refs provide a way to access DOM nodes or React elements created in the render method. Creating Refs: Refs are created using React. createRef() and attached to React elements via the ref attribute.
Firstly, npm install / yarn add the prop-types package if you haven't already. Then, add your propTypes (and defaultProps too if required) after the stateless functional component has been defined, before you export it.
PropTypes are simply a mechanism that ensures that the passed value is of the correct datatype. This makes sure that we don't receive an error at the very end of our app by the console which might not be easy to deal with.
PropTypes.instanceOf(Element)
Is working for me. You can also add isRequired:
PropTypes.instanceOf(Element).isRequired
You can check if the passed property is instance of Element
:
The Element interface represents an object of a Document. This interface describes methods and properties common to all kinds of elements. Specific behaviors are described in interfaces which inherit from Element but add additional functionality. For example, the HTMLElement interface is the base interface for HTML elements, while the SVGElement interface is the basis for all SVG elements.
class Some extends React.Component {
render() {
return (
<div> Hello </div>
);
}
}
const validateDOMElem = (props, propName, componentName) => {
if (props[propName] instanceof Element === false) {
return new Error(
'Invalid prop `' + propName + '` supplied to' +
' `' + componentName + '`. Validation failed.'
);
}
}
Some.propTypes = {
htmlElem: validateDOMElem,
};
const para = document.getElementById('para');
ReactDOM.render(<Some htmlElem={para} />, document.getElementById('app'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.js"></script>
<div id="app"></div>
<p id="para"></p>
For example with a list component:
MyList.propTypes = {
children: PropTypes.instanceOf(<li></li>),
}
Works for me.
PropTypes.instanceOf(Element)
will not work for server-side render, because of ReferenceError: Element is not defined
Suggest using PropTypes.object
instead
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