Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if variable is React node or array

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.

like image 495
ThomasReggi Avatar asked Sep 17 '15 16:09

ThomasReggi


People also ask

How do you check if data is an array in React?

To check if an element exists in an array in React: Use the includes() method to check if a primitive exists in an array. Use the some() method to check if an object exists in an array.

How do you identify the components of a React?

Open the console by either right-clicking and inspecting an element or by opening the toolbar by clicking View > Developer > JavaScript console. The Components tab will show the current React component tree, along with any props, state, or context.

Is a string a React node?

React.Node can be null, a boolean, a number, a string, a React element, or an array of any of those types recursively. If you need a return type for your component render() methods then you should use React.

Are children reacting arrays?

To learn more about this, check out this article. This will work fine if there are multiple children elements, but if there is only a single child then the map method will fail because as seen at the beginning If there is only a single element then props. children will be a string and not an array.


1 Answers

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

React.isValidElement() 
like image 183
ThomasReggi Avatar answered Oct 01 '22 22:10

ThomasReggi