Search code examples
javascriptreactjsecmascript-6react-bootstrap

how can I persist state on React-Bootstrap Accordion using useState?


I'm trying to save the state of a React-Bootstrap Accordion in localStorage using useState hook.

Using the example on the React-Bootstrap docs website I know I can get the eventKey and control it using this. Using the examples on the website, which use the eventKey to customise a toggle button is slightly different from what I need and I can't seem to make the leap between them. I can save the eventKey to localStorage but I can't get it back into the eventKey prop.

Any help would be appreciated.


Solution

  • I would utilize the <Accordion> components onSelect prop and pass a function where you update a Hook's state and save that eventKey to localStorage.

    const [expandedItem, setExpandedItem] = useState("0")
    
    ...
    
    <Accordion
        defaultActiveKey={expandedItem}
        onSelect={(e) => {
            if (e !== null){ // if e === null, that means that an accordion item was collapsed rather than expanded. e will be non-null when an item is expanded
                setExpandedItem(e);
                localStorage.setItem('expandedItem', e);
            }
        }
    ...
    

    And if you wanted to have this Accordion open to the last item that was expanded by the user on page re-renders, you could amend the above to achieve that behavior:

    const [expandedItem, setExpandedItem] = useState(localStorage.getItem('expandedItem') ?? "0")
    

    ?? is the Nullish Coalescing Operator.

    Let me know if this answers your question. If this isn't really what you were looking for, maybe you can edit your original post with some more details or a code sample.