Question
How can I confirm that a react element received through props (like children
for example) is of a given type in my render method?
Example:
Say I have a List
element and a ListItem
element. In the render method of List
, I want to look for all of the children that were passed and do something special with any children that are ListItem
s.
I did find an implementation that works, but only after trial and error. See the code below. (React 15.4.2)
List.jsx
import ListItem from 'list-item';
...
React.Children.map(children, child => {
console.log(child); // function ListItem() { ... }
console.log(ListItem); // function ListItem() { ... }
if (isListItem(child)) {
return (...);
}
return child;
})
// this implementation does not work
isListItem(element) {
return (element.type === ListItem);
}
// this implementation does work, but might break if I'm using something like uglify or if I use `react-redux` and `connect()` ListItem (as that will change the display name)
isListItem(element) {
return (element.type.displayName === 'ListItem');
}
// this implementation does work
isListItem(element) {
return (element.type === (<ListItem />).type);
}
ListItem.jsx
class ListItem expends React.component {
...
}
export default ListItem;
So, the last implementation seems to work, but why doesn't the first implementation work? I can't find any material relating to this in the react documentation, though I did find some stack overflow questions about the same thing. The answers provided in those questions, however, indicate that the first implementation should work (though they are for older versions of React)