Search code examples
reactjsreact-hooksaccordionreact-bootstrap

React Accordion component, calling hook after handler from within collapse


I have a React Bootstrap accordion component. Within each of the cards of the accordion there is a task to complete and then a 'Save' button. This button writes the completed task to a database.

I also want the save button to collapse the current card and expand the next card. I can achieve this by creating a customer Button component that calls useAccordionToggle(eventKey) onClick (before calling children):

function AccordianButton({ children, eventKey }) {
    return (
      <Button
        onClick={useAccordionToggle(eventKey)}
      >
        {children}
      </Button>
    );
  }

So far so good!

The problem is that I only want to collapse the accordion card once I am sure the database write has been successful.

I can't figure out a way to do this. If I try to call useAccordionToggle in the handler function I get a hook error because I'm outside the component. Is there a way to do this?


Solution

  • I've realised you can use an activeKey parameter and drive this using a state from the React component, and thus control from anywhere. Much easier than using the eventKey parameters.