1
0
mirror of https://github.com/jbranchaud/til synced 2026-01-03 07:08:01 +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

@@ -10,7 +10,7 @@ smart people at [Hashrocket](http://hashrocket.com/).
For a steady stream of TILs from a variety of rocketeers, checkout
[til.hashrocket.com](https://til.hashrocket.com/).
_735 TILs and counting..._
_736 TILs and counting..._
---
@@ -481,6 +481,7 @@ _735 TILs and counting..._
- [Allow md As An Extension With gatsby-mdx](react/allow-md-as-an-extension-with-gatsby-mdx.md)
- [Alter The Display Name Of A Component](react/alter-the-display-name-of-a-component.md)
- [Building A React App In The Browser](react/building-a-react-app-in-the-browser.md)
- [Check The Type Of A Child Component](react/check-the-type-of-a-child-component.md)
- [Create Dynamically Named Custom React Components](react/create-dynamically-named-custom-react-components.md)
- [create-react-app Comes With Lodash](react/create-react-app-comes-with-lodash.md)
- [create-react-app Has A Default Test Setup File](react/create-react-app-has-a-default-test-setup-file.md)

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)