jsindos
jsindos

Reputation: 539

Rendering a redux component with and without children

I've noticed that children nodes of a Redux container can automatically get passed as props to the wrapped component:

<Container>
  Child Text
</Container>

Container.js:

const Container = connect()(Component)

Component.js:

const Component = ({ children }) => {
  if (children) {
    return (
      <p>
        {children}
      </p>
    )
  }

  return (
      <p>
        No Child Text
      </p>
  )
}

Component.propTypes = {
  children: PropTypes.node.isRequired,
}

If I now render:

<Container>
    Child Text
</Container>
<Container/>

I get a warning for <Container/>:

Warning: Failed propType: Required prop 'children' was not specified in 'Component'

I'm wondering how to avoid this warning whilst being able to render both variations of my component.

Upvotes: 2

Views: 92

Answers (1)

Elod Szopos
Elod Szopos

Reputation: 3526

Simply remove the .isRequired

from

Component.propTypes = {
   children: PropTypes.node.isRequired,
}

You basically told the container that children prop will be a required one, so React warns you if it's missing.

Upvotes: 1

Related Questions