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?
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?
PropTypes.instanceOf(Element)
Is working for me. You can also add isRequired:
PropTypes.instanceOf(Element).isRequired
PropTypes.elementType
as explained here: #48007826 –
Rollmop Element
will be undefined
in nodejs. If you strip out your PropTypes from your production build you will be fine there. But even so, you'll throw an error in the development build. –
Tragedy PropTypes.elementType
is NOT for native DOM element instances. See here: github.com/facebook/prop-types/issues/334 and here: github.com/facebook/prop-types/pull/211 –
Abagael 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>
PropTypes.instanceOf(Element)
–
Curiosity For example with a list component:
MyList.propTypes = {
children: PropTypes.instanceOf(<li></li>),
}
Works for me.
Failed prop type: Right-hand side of 'instanceof' is not callable
if I use this, does this not work anymore in 2019? –
Oppressive PropTypes.instanceOf(Element)
will not work for server-side render, because of ReferenceError: Element is not defined
Suggest using PropTypes.object
instead
© 2022 - 2024 — McMap. All rights reserved.
someNode.constructor.name
. – Foreordaindiv
,span
,input
, whatever. – ApivorousReact.PropTypes.node
? – Molluscdocument.getElementById
or created withdocument.createElement
and notReact.createElement("input")
? – Apivorousnode
is too loose. It includes numbers, strings and arrays. – Apivorous