Reputation: 180
i have a question, i'm not sure if possible or not. Here is a sample code. I have a component, i want everytime they use my component and a children it should only accept the specific component.
for e.g:
<tableComponent>
<tableHeaderComponent/>
<tableHeaderComponent/>
<tableHeaderComponent/>
</tableComponent>
but for this type it should not be accepted
<tableComponent>
<th>blah</th>
<th>blah2</th>
<yourowncomponent/>
</tableComponent>
thanks, ping pong
Upvotes: 1
Views: 718
Reputation: 11770
Assign a displayName
to the component you want to allow and check inside the parent component if the children have the allowed displayName
const Good = () => <h1>Good</h1>;
Good.displayName = "Good";
const Bad = () => <h1>Bad</h1>;
const WithGoodOnly = ({ children }) => {
let allowed;
if (Array.isArray(children)) {
allowed = children.every(child => child.type.displayName === "Good");
} else {
allowed = children.type.displayName === "Good";
}
return allowed ? <div>{children}</div> : null;
};
rendered
const App = () => (
<WithGoodOnly>
<Good />
</WithGoodOnly>
);
rendered
const App = () => (
<WithGoodOnly>
<Good />
<Good />
</WithGoodOnly>
);
not rendered
const App = () => (
<WithGoodOnly>
<Good />
<Bad />
</WithGoodOnly>
);
Upvotes: 1