Accessing React.children props

I have a component that accepts children of a specific element type and then React.children.maps over it. Inside the component I want to read the props of the elements and map it to something else

A basic example (Pick out the title prop of all children and map it to just the string element of that title)

<div>
    { React.Children.map(children, el => el.props.title->React.String) }
</div>

How can I do this? I’m quite new to rescript, my feeling is that I have to write some type mappings for this…

Is it even allowed in React? Looks like you rely on the frameworks internal implementation that might change any time. It should be done in a different way in React. One of the ways is to pass an array of titles as a separate prop and render them inside of the component.

I think it’s pretty common pattern in design libraries. Not sure how internal it is, it’s a React.Element type.

Here’s a simple example working with typescript types at least

Maybe somethings like this?

@get
external getProps: React.element => {..} = "props"

module Foo = {
  @react.component
  let make = (~children: React.element) => {
    children->React.Children.map(el => {
      let props = el->getProps
      props["title"]->React.string
    })
  }
}
1 Like