Mel
Mel

Reputation: 2715

how to conditionally render a server component depending on the state set in client component?

I'm trying to use a tailwinds css template sidebar, which updates the main div, with components, depending on the active sidebar tab. I need to use state to check which sidebar tab is active - so the dashboard menu has to be a client component.

I'm fetching data for various tabs in the main div.

export default function DashboardPage() {

    const [activeTab, setActiveTab] = useState('');

{navigation.map((item) => (
                      <li key={item.name}>
                        <a
                          href={item.href}
                          onClick={() => setActiveTab(item.name)}
                          className={classNames(
                            item.current
                              ? ' text-tip'
                              : 'text-linkStyle hover:text-linkOnHover ',
                            'group flex gap-x-3 rounded-md p-2 text-sm leading-6 font-normal'
                          )}
                        >

Then in the main div, I render different components (which are server components) in depending on which sidebar tab is active:

<main className="py-10 z-20 px-2">
            <div className="mx-auto max-w-7xl px-4 sm:px-6 lg:px-8">
                {activeTab === 'Publications' && <><FeedForm /> </>}
                {activeTab === 'Publishers' && <PublishersList />}
            </div>
          </main>

I can't render server components into a client component. I also can't make the dashboard a layout that has the server components as direct children, because the state of the active sidebar tab determines whether that main div component is rendered.

How can I do this in nextjs 13 server components?

Upvotes: 1

Views: 976

Answers (1)

Abhishek Ranjan
Abhishek Ranjan

Reputation: 243

Instead of using a state variable for activeTab, use a query param for it and on click push this query param to router. Then inside a parent server component conditionally render <FeedForm /> & <PublishersList /> based on this query param.

Upvotes: 0

Related Questions