0

I am working on a generic component which has some sub-components that are wrapped into the main component like this:

<Main>
    <Main.First />
    <Main.Second />
    <Main.Third />
</Main>

The main point here is that I want to prevent any component which is not Main. from being wrapped into the component so for instance:

<Main>
  <span>any random text</span>
</Main>

This should return an error. I am using react.cloneElement to render the child components of the Main component and I want to add this condition. Here is how I loop over it

React.Children.toArray(children).map(child => child)

Any ideas?

Thanks in advance.

Saif
  • 249
  • 5
  • 15
  • A TypeScript approach to this problem: [Only allow specific components as children in React and Typescript](https://stackoverflow.com/questions/57627929/only-allow-specific-components-as-children-in-react-and-typescript) And an old but possibly useful JS version: [Only allow children of a specific type in a react component](https://stackoverflow.com/questions/27366077/only-allow-children-of-a-specific-type-in-a-react-component) – DBS May 09 '23 at 10:51

0 Answers0