How to check if element is valid JSX

Viewed 3721

Is it possible to check if object is JSX maybe some function that do that. I'm interested in React and Preact.

var x = <App/>
var y = <div>xxx</div>

I came up with this:

function isJSX(x) {
   return typeof x.props === 'object' && x.props !== null && typeof x.type !== 'undefined';
}

Is there a better way? I'm not sure about other libraries like HyperApp and Preact. Is this function reliable? The output came from Babel. Is there a spec that show what should be the output of JSX transpiler?

Here is my testing Pen

2 Answers

jsx is mainly syntactic sugar for React.createElement. You can use isValidElement a helper provided by React to check if a given element is valid.

const isValid = React.isValidElement(element)
Related