bootstrap react Accordion – collapse / expand via useState

  Kiến thức lập trình

I’ve a react-accordion component with multiple ‘cards’.
Initially the first is expanded and the rest is collapsed.
I would like to control the state (collapsed/expanded) via a react state (useState).

I’ve seen the examples in the docs how to control the button behavior but this is not exactly what I like to do.

I’ve created the following which does update the sate but doesn’t collapse/expand the “1” card

import Accordion from 'react-bootstrap/Accordion';
import { useState } from 'react';


function App() {
  const [acitveCard, setAcitveCard] = useState("0");

  return (
    <>
    <Accordion defaultActiveKey={acitveCard}>
      <Accordion.Item eventKey="0">
        <Accordion.Header>#1</Accordion.Header>
        <Accordion.Body>
        accor body 1 : active card= {acitveCard}
        </Accordion.Body>
      </Accordion.Item>
      <Accordion.Item eventKey="1">
        <Accordion.Header>#2</Accordion.Header>
        <Accordion.Body>
        accor body 2: active card = {acitveCard}
        </Accordion.Body>
      </Accordion.Item>
    </Accordion>
    <button type="button" onClick={() => setAcitveCard("1")} >collapse switch 1</button>
    </>
  );
}

export default App;

Theme wordpress giá rẻ Theme wordpress giá rẻ Thiết kế website

LEAVE A COMMENT