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.
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.
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.
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.
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.
React has a function just to check if a variable is an element, here's the docs.
React.isValidElement()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With