React: How to pass multiple server components to a client component?

682 Views Asked by At

Since React doesn't allow importing Server components inside Client components, one workaround is creating an outer Server component, and inside it rendering the Client component with the other Server component passed to it as a child. That's okay, but I don't understand how can I pass multiple Server children to the Client component while being able to extract them from children prop and place anywhere I like. Any ideas ?

This is not possible:

// ServerComp.server.jsx

export default function ServerComp() {
  return <div>Server component</div>
}

// ClientComp.client.jsx

import ServerComp from "./ServerComp.server"; // This is not allowed in client component

export default function ClientComp() {
  <div>
    <h1>Rendering Server component like this ISN'T possible</h1>
    <ServerComp />
  </div>
}

But this is possible:

...

// ClientComp.client.jsx

export default function ClientComp({children}) {
  return <div>
    <h1>Rendering Server component like this IS possible</h1>
    {children}
  </div>
}

// OuterServerComp.server.jsx

import ClientComp from "./ClientComp.client";
import ServerComp from "./ServerComp.server";

export default function OuterServerComp() {
  return (
    <ClientComp>
      <ServerComp />
    </ClientComp>
)
}

But how can I do this ?

...

// ClientComp.client.jsx

export default function ClientComp({children}) {
  return <div>

    // Here I want to be able to extract 1st child and place it here.
    // Something like this: {children[0]}
    
    <h1>Some other content in between</h1>
    <div>
    
       // And then I want to extract and place second children here.
       //Something like this: {children[1]}
    
    </div>
  </div>
}

// OuterServerComp.server.jsx

import ClientComp from "./ClientComp.client";
import ServerComp from "./ServerComp.server";

export default function OuterServerComp() {
  return (
    <ClientComp>

      // Passing multiple server components
    
      <ServerComp />
      <ServerComp />
    </ClientComp>
)
}
0

There are 0 best solutions below