3

I have an accordion that opens when I click on the header. I also added a chevron that I want to change the direction when it opens. I'm not sure how to do that with the accordion since I'm not changing states based on a button click. My accordion code:

    <Accordion defaultActiveKey="0">
      <Card>
        <Accordion.Toggle as={Card.Header} eventKey="1">
          Roll History <FaChevronDown />
        </Accordion.Toggle>
        <Accordion.Collapse eventKey="1">
          <Card.Body>{historyText}</Card.Body>
        </Accordion.Collapse>
      </Card>
    </Accordion> 

When the accordion opens, I want to show FaChevronUp instead?

baumli
  • 421
  • 5
  • 24

2 Answers2

6

Declare the hook:

  const [open, setOpen] = useState(false);

on here add the following:

 <Accordion.Toggle as={Card.Header} eventKey="1" onClick={() => setOpen(!open)}>
   Roll History { open ? <FaChevronDown /> : <FaChevronUp/> }
 </Accordion.Toggle>**

With this:

onClick={() => setOpen(!open)} you are toggeling the hook state, this onClick should be placed on the element that Open/Closes the element when you click.

yuri
  • 3,182
  • 2
  • 16
  • 26
  • Perfect, I did reverse the chevrons since when I click, it opens below, but otherwise worked exactly like I wanted, thanks! – baumli Dec 25 '19 at 15:17
  • 1
    If you have multiple accordions this will open all of them. – Randall Apr 03 '20 at 10:56
  • Please pay attention to functional updates mentioned in https://reactjs.org/docs/hooks-reference.html#functional-updates – Samuel Zhang May 16 '20 at 15:23
  • Also need to add `in={open} ` in ``, In my case Body part is not expanded so I added `` – Vijay Aug 08 '21 at 06:58
0

Also to resolve multiple tabs set a new state to save the index then check if this is the tab you're opening

const [activeTab, setActiveTab] = useState(0)

             <Card key={index}>
              <Card.Header>
                 <Accordion.Toggle
                    onClick={() => {
                       setOpen(!open)
                       setActiveTab(index)
                    }}
                    as={Card.Header}
                    variant="link"
                    eventKey={`${index}`}
                 >
                    {d.name}{' '}
                    {open && activeTab === index ? (
                       <FaChevronDown />
                    ) : (
                       <FaChevronUp />
                    )}
                 </Accordion.Toggle>
              </Card.Header>
              <Accordion.Collapse eventKey={`${index}`}>
                 <Card.Body>{d.component}</Card.Body>
              </Accordion.Collapse>
           </Card>enter code here
joanis
  • 10,635
  • 14
  • 30
  • 40