Home > database >  start an accordion menu on a specific item in react
start an accordion menu on a specific item in react

Time:12-28

I'm using ChakraUI for React. The accordion docs are very helpful, but I'm not sure how to make the accordion automatically open on a particular choice. I've read through the docs and I don't quite understand how this would be done. Here are the docs: https://chakra-ui.com/docs/disclosure/accordion

So far I've used this example:

import {
  Accordion,
  AccordionItem,
  AccordionButton,
  AccordionPanel,
  AccordionIcon,
} from '@chakra-ui/react'

...
<Accordion>
  <AccordionItem>
    <h2>
      <AccordionButton>
        <Box flex='1' textAlign='left'>
          Section 1 title
        </Box>
        <AccordionIcon />
      </AccordionButton>
    </h2>
    <AccordionPanel pb={4}>
      Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod
      tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim
      veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea
      commodo consequat.
    </AccordionPanel>
  </AccordionItem>

  <AccordionItem>
    <h2>
      <AccordionButton>
        <Box flex='1' textAlign='left'>
          Section 2 title
        </Box>
        <AccordionIcon />
      </AccordionButton>
    </h2>
    <AccordionPanel pb={4}>
      Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod
      tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim
      veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea
      commodo consequat.
    </AccordionPanel>
  </AccordionItem>
</Accordion>

based on the docs there are a number of properties I've tried to no avail. I've tried adding defaultIndex as a prop for the <Accordion /> but i'm not sure how to set the actual index. For example <Accordion defaultIndex=0 /> is not allowed. I'm not sure how to use that.

Thank you

CodePudding user response:

From the docs

If you pass this prop, ensure that the index or defaultIndex prop is an array.

Try like below

<Accordion defaultIndex={[0]}>
  ...
  ...
</Accordion>
  • Related