29

How do I iterate through a React component's children in Typescript tsx?

The following would be valid jsx:

public render() {
    return (
        <div>
            {React.Children.map(this.props.children, x => x.props.foo)}
        </div>
    );
}

However, in Typescript, the type of x is React.ReactElement<any> so I have no access to props. Is there some kind of casting that I need to do?

Dmitry Shvedov
  • 3,169
  • 4
  • 39
  • 51
CookieOfFortune
  • 13,836
  • 8
  • 42
  • 58

3 Answers3

30

Using any should generally be avoided as you're losing the type info.

Instead use React.ReactElement<P> in the function parameter type:

React.Children.map(this.props.children, (child: React.ReactElement<ChildPropTypes>) => child.props.bar)
Ian Chadwick
  • 1,547
  • 1
  • 19
  • 21
21

However, in Typescript, the type of x is React.ReactElement so I have no access to props. Is there some kind of casting that I need to do?

Yes. Also prefer the term assertion. A quick one:

React.Children.map(this.props.children, x => (x as any).props.foo)
basarat
  • 261,912
  • 58
  • 460
  • 511
0
import React, {FC, Children, isValidElement } from "react"



 const MyComponent: FC = ({children}) => {
    // define component logic
    return ( 
    // children is a prop that passed to the component
    // second arg is a callback
    { Children.map(children, child => {
              // if child is a valid element, we can set attributes
              // you might need to add attributes dynamically
              if (isValidElement(child)) {
                return {
                  ...child,
                  props: {
                    ...child.props,
                    className:"Add className here"
                  }
                }
               }
              // if element is not valid just return child
              return child
    })
Yilmaz
  • 35,338
  • 10
  • 157
  • 202