reactjsreact-propschildren

How to access data in React.Children or props.children?


So I'm trying to get some data from props.children or React.Children but I'm not being able to, this is what I'm doing:

console.log(props.children)

This prints this on the console:

[
  0: {
     $$typeof: Symbol(react.element)
     key: "slide-id-0"
     props: {section: {…}, onChange: ƒ}
     ...
  }
  1: {
     $$typeof: Symbol(react.element)
     key: "slide-id-1"
     props: {section: {…}, onChange: ƒ}
     ...
  }

]

And if i try to loop through it like this:

React.Children.map(children, child => (
        console.log(child)
    ))

I get the two objects:

0: {
     $$typeof: Symbol(react.element)
     key: "slide-id-0"
     props: {section: {…}, onChange: ƒ}
     ...
  }
  1: {
     $$typeof: Symbol(react.element)
     key: "slide-id-1"
     props: {section: {…}, onChange: ƒ}
     ...
  }

Now, what I want is to access the section inside the props component inside the object, but if I try to do this:

React.Children.map(children, child => (
        console.log(child.props)
    ))

I get this error:

Property 'props' does not exist on type 'string | number | boolean | {} | ReactElement<any, string | JSXElementConstructor> | ReactNodeArray | ReactPortal'. Property 'props' does not exist on type 'string'.ts(2339)

How can I access that data?


Solution

  • I finally got it working, i used this other question as reference: React.Children.map recursively

    And i this is what i did:

    React.Children.map(children, child => {
            if (!React.isValidElement(child)) {
              return child;
            }
        
            if (child.props) {
                console.log(child.props.section)
            }
        })