defaultValue Prop Not Working as Expected in Radix UI Accordion with Dynamic Children

131 Views Asked by At

Description: I'm using Radix UI's Accordion component in a Next.js project and encountering an issue where the defaultValue prop doesn't seem to work when the Accordion's children are dynamically generated. Despite setting defaultValue, the accordion items do not open by default as expected.

Code Snippet: Here's how I've set up my accordion components:

Page code:

<AccordionContextProvider>
  <div className="w-full">
    <TotalIngresosThisMonth />
  </div>
  <ClientSideAccordionManager>
    <AccordionContentWrapper itemId="item-1" title="Administrar ingresos">
      {/* Content for item-1 */}
    </AccordionContentWrapper>
    <AccordionContentWrapper itemId="item-2" title="Administrar fuente de ingresos">
      {/* Content for item-2 */}
    </AccordionContentWrapper>
    {/* Additional sections if needed */}
  </ClientSideAccordionManager>
</AccordionContextProvider>

ClientSideAccordionManager:

export const ClientSideAccordionManager: React.FC<{ children: React.ReactNode }> = ({ children }) => {
  const { openItems, setOpenItems } = useAccordionContext();

  const handleValueChange = (value: string[]) => {
    setOpenItems(value);
  };

  return (
    <Accordion
      type="multiple"
      defaultValue={["item-1"]} // Attempted to set item-1 as the default open item
      value={openItems}
      onValueChange={handleValueChange}
    >
      {children}
    </Accordion>
  );
};

AccordionContentWrapper:

"use client";
import { AccordionContent, AccordionItem, AccordionTrigger } from '@/components/ui/accordion';
import React from 'react';

export const AccordionContentWrapper: React.FC<{
  itemId: string;
  title: string;
  children: React.ReactNode;
}> = ({ itemId, title, children }) => {
  return (
    <AccordionItem value={itemId}>
      <AccordionTrigger>{title}</AccordionTrigger>
      <AccordionContent>{children}</AccordionContent>
    </AccordionItem>
  );
};

Expected Behavior: I expect the accordion item specified in the defaultValue prop to be open by default when the page loads.

Actual Behavior: The accordion does not open any items by default, regardless of the defaultValue specified.

Question: Could the issue be related to how the children prop is used or possibly a misunderstanding of how defaultValue should work with dynamically generated children? Any insights or suggestions on how to resolve this issue would be greatly appreciated.

0

There are 0 best solutions below