Liz
Liz

Reputation: 13

Stop accordion collapsing on checking checkbox in react

Using react-bootstrap accordion. The 1st accordion remains open all the time. However when i click checkbox inside 2nd accordion it collapses the accordion. I've tried putting an onClick on the checkboxes and then e.stopPropagation(). This does not work. The accordion is a child of main page & checkboxes children of accordion. The checkboxes on change is passed from main to accordion as property. This is onchange function for checkboxes on main page.

const handleOnChange = (position) => {
// position used to save details to state in main page
}

This is the accordion component

const AccordionComp = ({ list, handleOnChange, checkedState }) => {
  return (
    <Accordion defaultActiveKey={["0"]} alwaysOpen flush>
      <Accordion.Item eventKey="0">
        <Accordion.Header>Popular</Accordion.Header>
        <Accordion.Body>
          <Row className="justify-content-md-center pt-2" key={1}>
            <Col className="optionCheckbox mx-10">
              {list.slice(0, 11).map((eq, idx) => (
                <Form.Group key={idx}>
                  <Form.Check
                    type="checkbox"
                    name={eq.name}
                    id={`options-${eq._id}`}
                    label={eq.name}
                    checked={checkedState[idx]}
                    onChange={(e) => handleOnChange(e, idx)}
                  />
                </Form.Group>
              ))}
            </Col>
          </Row>
        </Accordion.Body>
      </Accordion.Item>
      <Accordion.Item eventKey="1">
        <Accordion.Header>Other</Accordion.Header>
        <Accordion.Body>
          <Row className="justify-content-md-center pt-2" key={1}>
            <Col className="optionCheckbox mx-10">
              {list.slice(12, 24).map((eq, idx) => {
                let newIndex = 12 + idx;
                return (
                  <Form.Group key={newIndex}>
                    <Form.Check
                      type="checkbox"
                      name={eq.name}
                      id={`options-${eq._id}`}
                      label={eq.name}
                      checked={checkedState[newIndex]}
                      onClick={(e) => e.stopPropagation()}
                      onChange={(e) => handleOnChange(e, newIndex)}
                    />
                  </Form.Group>
                );
              })}
            </Col>
          </Row>
        </Accordion.Body>
      </Accordion.Item>
    </Accordion>
  );
};

Any help to stop 2nd accordion collapsing until directly requested would be very gratefully received. Thank you

Upvotes: 0

Views: 831

Answers (1)

Maitri
Maitri

Reputation: 3

please check the version of react-bootstrap. using 2.8.0 working fine for me.

https://codesandbox.io/s/react-bootstrap-accordion-forked-c4kzd3?file=/src/App.js

Upvotes: 0

Related Questions