0

An example will explain better then I can ever formulate it

In below code, how to pass the index to Child when Child is passed in as a prop

const ComponentA = (props) => {
  return (
    <div>
      { data.map((item,index) => {
          return (
            <Child index={index} />
          );
        })
      }
    </div>
  )
}

So my component A would look like this, and I want to pass the index to (each of) the children

const ComponentA = (props) => {
  return (
    <div>
      { data.map((item,index) => {
          return (
            {props.children}
          );
        })
      }
    </div>
  )
}

thanks

user901926
  • 21
  • 2

1 Answers1

0

Use React.cloneElement:

return <div>{React.cloneElement(props.children, { index: index })}<\div>

https://reactjs.org/docs/react-api.html#cloneelement

How to pass props to {this.props.children}