1
0
mirror of https://github.com/jbranchaud/til synced 2026-01-09 18:18:02 +00:00

Add Check The Type Of A Child Component as a React til

This commit is contained in:
jbranchaud
2019-01-10 16:46:15 -06:00
parent 0e9e4b9d57
commit 7d77cd9812
2 changed files with 35 additions and 1 deletions

View File

@@ -0,0 +1,33 @@
# Check The Type Of A Child Component
There is a simple way to check the type of a child component.
```javascript
import React from 'react';
const Hello = () => <h1>Hello</h1>;
const Greeting = ({ children }) => {
let hello;
React.Children.forEach(children, child => {
if(child.type === Hello) {
hello = child;
}
});
return hello;
};
```
This is a comparison of the child's type to the component constant we are
looking for.
This comparison is not the most robust. For instance, Gatsby does something
internally that throws off this comparison. Here is a more robust
comparison.
```javascript
if(child.type === Hello || child.type === <Hello />.type)
```
[source](https://github.com/gatsbyjs/gatsby/issues/3486)