Home > Net >  How to pass props to {children} and use it?
How to pass props to {children} and use it?

Time:04-23

I am trying to make a reusable react input element. React version: "react": "17.0.2"

I want to pass htmlFor in the label and use the same in the children id property. So I am trying to pass props to {children} in react. I have tried type error

CodePudding user response:

You're getting this type error because React.cloneElement() requires an Element to clone; children is not guaranteed to be an element. It's a ReactNode, which is a type alias that includes undefined and null. Those are valid types to return from a React component, but not to pass to cloneElement. You could do this instead:

children = React.Children.map(children, el => {
  return React.cloneElement(el, { id: label })
})

This would allow you to clone each element in turn. If you only expect a single element, React.Children.only() can be used in a similar way

children = React.Children.only(children)
children = React.cloneElement(children)
  • Related