ping pong
ping pong

Reputation: 180

Limit child components in a react component

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

Answers (1)

Asaf Aviv
Asaf Aviv

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

Related Questions