I have a component that accepts children, what I want to do is limit the number of children to only one, I want the child to be a single view or single text in react native
Asked
Active
Viewed 1,183 times
1
-
We would appreciate if you give more info on this, for starters you can add code which you have tried so far. – Nakul Nov 02 '18 at 11:16
-
I have not tried anything yet. – Ammar Tariq Nov 02 '18 at 11:21
1 Answers
2
You can use React.Children
API, specifically React.Children.only
.
I believe the proper syntax is:
class MyComponent extends React.Component {
render(){
return React.Children.only(this.props.children)()
}
}
This will verify that there is only one child, and return that child, or throw an error if there is more than one child.
You can also use PropTypes
class MyComponent extends React.Component {
render(){
const children = this.props.children
return (
<>
{children}
</>
)
}
}
MyComponent.propTypes = {
children: PropTypes.element.isRequired
}
If you would further like to enforce that your child is only a Text
or View
instance, you can write a custom PropTypes
validator, here is an example on StackOverflow

Robbie Milejczak
- 5,664
- 3
- 32
- 65
-
Thank your for your support, I used proptype menu worked fine for me :) – Ammar Tariq Nov 02 '18 at 14:29