Check if variable is React node or array

JavascriptPropertiesReactjs

Javascript Problem Overview


I'd like to have a condition that states if a prop is a React node then just place it as a child within a component, and if it's not, take some action to make it into a component. This way my component will be able to accept this prop as an array of strings, or an array of nodes.

I tried to check if React.PropTypes.node would return a boolean but it doesn't work.

Say I have a module called List and there's a prop called items. I'd like to be able to pass

var items = [  "One",  "Two",  "Three"]

as well as

var items = function () {
  return (
    <li>One</li>
    <li>Two</li>
    <li>Three</li>
  )
}

And within the component have some logic that would detect the difference and if it's a plain array (not an array of nodes) be able to map the items.

Javascript Solutions


Solution 1 - Javascript

React has a function just to check if a variable is an element, here's the docs.

React.isValidElement()

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionThomasReggiView Question on Stackoverflow
Solution 1 - JavascriptThomasReggiView Answer on Stackoverflow