53
votes

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.

1

1 Answers

98
votes

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

React.isValidElement()