vivek singh
vivek singh

Reputation: 457

How to toggle plus to minus and vice-versa in bootstrap Accordion

I am woking on Accordion using react-bootstrap I have successfully created the Accordion, Now I want to provide toggle to the each header like plus minus when it is open show - sing when it is closed show plus sign, But I am not able to handle the event

What I have Done

import React from "react";
import "./styles.css";
import { Accordion, Card } from "react-bootstrap";

const App = () => {
  const data = [
    { name: "mike", age: 22 },
    { name: "clive", age: 25 },
    { name: "morgan", age: 82 }
  ];
  return (
    <div className="App">
      <Accordion defaultActiveKey="0">
        {data.map((item, index) => (
          <Card>
            <Accordion.Toggle as={Card.Header} eventKey={index}>
              {item.name}
            </Accordion.Toggle>
            <Accordion.Collapse eventKey={index}>
              <Card.Body>{item.age}</Card.Body>
            </Accordion.Collapse>
          </Card>
        ))}
      </Accordion>
    </div>
  );
};
export default App;

I am using this

Working Code sandbox

Upvotes: 2

Views: 4457

Answers (1)

ROOT
ROOT

Reputation: 11622

You can just create a custom Accordion.Toggle# with custom onclick event, also use useState to handle the toggle event that set +/- signs:

Here is a snippet or sandbox:

import React, { useState } from "react";
import "./styles.css";
import { Accordion, Card, useAccordionToggle } from "react-bootstrap";

function CustomToggle({ children, eventKey, handleClick }) {
  const decoratedOnClick = useAccordionToggle(eventKey, () => {
    handleClick();
  });

  return (
    <div className="card-header" type="button" onClick={decoratedOnClick}>
      {children}
    </div>
  );
}

const App = () => {
  const [activeKey, setActiveKey] = useState(0);

  const data = [
    { name: "mike", age: 22 },
    { name: "clive", age: 25 },
    { name: "morgan", age: 82 }
  ];
  return (
    <div className="App">
      <Accordion defaultActiveKey={0} activeKey={activeKey}>
        {data.map((item, index) => (
          <Card key={index}>
            <CustomToggle
              as={Card.Header}
              eventKey={index}
              handleClick={() => {
                if (activeKey === index) {
                  setActiveKey(null);
                } else {
                  setActiveKey(index);
                }
              }}
            >
              {item.name}
              {activeKey === index ? "-" : "+"}
            </CustomToggle>
            <Accordion.Collapse eventKey={index}>
              <Card.Body>{item.age}</Card.Body>
            </Accordion.Collapse>
          </Card>
        ))}
      </Accordion>
    </div>
  );
};
export default App;

Upvotes: 2

Related Questions