Ammar Tariq
Ammar Tariq

Reputation: 847

How to restrict the number of child in a component to only one in react native?

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

Upvotes: 1

Views: 1406

Answers (1)

Robbie Milejczak
Robbie Milejczak

Reputation: 5780

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

Upvotes: 2

Related Questions