Parents with specific children types

You can tell Flow that a component should only work with specific types of child components. Let's say that you have a Child component, and this is the only type of component that should be allowed as a child of the component you're working on. Here's how you can tell Flow about this constraint:

// @flow 
import * as React from 'react'; 
import Child from './Child'; 
 
type Props = { 
  children: React.ChildrenArray<React.Element<Child>>, 
}; 
 
const Parent = ({ children }: Props) => ( 
  <section> 
    <h2>Parent</h2> 
    {children} 
  </section> 
); 
 
export default Parent; 

Let's start with the first import statement:

 import * as React from 'react'; 

The reason that you want to import the asterisk as React is because this will pull in all of the Flow type declarations available within React. In this example, you're using the ChildrenArray type to specify that the value is in fact a child of the component, and Element to specify that you need a React element. The type argument that's used in this example tells Flow that the Child component is the only type of component that's acceptable here.

This JSX will pass flow validation, given the child constraints:

<Parent> 
  <Child /> 
  <Child /> 
</Parent> 

There's no restriction on the number of Child components that are rendered as children of Parent, just as long as there's at least one.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.147.61.142