Search code examples
reactjsreact-proptypes

What should be the prop type of passing a variable down in a child component via function


Given the following component:

Component.propTypes = {
  // not right:
  children: PropTypes.oneOfType([
    PropTypes.arrayOf(PropTypes.node),
    PropTypes.node,
  ]),
}

export default function Component({ children }) {
  return children({ someValue: "foobar" });
}
AnotherComponent.propTypes = {
  value: PropTypes.string,
}

export default function AnotherComponent({ value }) {
  return <p>{value}</p>
}

Used like:

<Component>
 {(someValue) => (<AnotherComponent value={someValue} />)}
</Component>

Gives the error: Warning: Failed prop type: Invalid prop 'children' supplied to 'Component'.

What is the proptype for this?


Solution

  • Try PropTypes.func:

    Component.propTypes = {
      children: PropTypes.func
    };
    

    Edit great-bird-qusxk

    As for "real-life" example, you can check the children type of AutoSizer [2]