CaribouCode
CaribouCode

Reputation: 14398

React propTypes for specific children components

I have a function component like so:

const Foo = () => <div>Hello world</div>;

Now I have another component that accepts children but should be restricted to 1 or more of the Foo component specifically (no other components allowed).

const Bar = ({ children }) => <div>{children}</div>;

How do I set propTypes on Bar to achieve this validation?

Bar.propTypes = {
  children: PropTypes.oneOf([
    PropTypes.arrayOf(PropTypes.node),
    PropTypes.node,
  ]);
};

The above is too loose because it will let any component type as children. How do I limit it to only allow Foo?

Upvotes: 0

Views: 148

Answers (1)

Zohaib Ijaz
Zohaib Ijaz

Reputation: 22885

You can use PropTypes.shape

Bar.propTypes = {
  children: PropTypes.oneOfType([
    PropTypes.shape({
      type: PropTypes.oneOf([Foo]),
    }),
    PropTypes.arrayOf(
      PropTypes.shape({
        type: PropTypes.oneOf([Foo]),
      })
    ),
  ]).isRequired
};

Upvotes: 3

Related Questions