bootstrap-5accordionreact-bootstrap

How to make an accordion colored?


I successfully made the inside of an accordion in React Bootstrap colored red, but its header remains non-red. Please, help to make the header red, too (it should be red when closed and light-red when open).

<Accordion defaultActiveKey={undefined}>
    <Accordion.Item eventKey="dangerZone">
        <Accordion.Header
            onClick={() => setShowDanger(!showDanger)}
            className="bg-red-500"
        >{showDanger ? "Hide danger zone" : "Show danger zone"}
        </Accordion.Header>
        <Accordion.Body style={{background: 'red'}}>
            <p><Button disabled={!isAuthenticated} onClick={uninstall}>REMOVE PACKAGE AND ALL ITS DATA</Button></p>
        </Accordion.Body>
    </Accordion.Item>
</Accordion>

Solution

  • This is how the DOM looks for the accordion header when rendered in a browser:

    <div class="accordion-item">
      <h2 class="bg-red-500 accordion-header">
        <button type="button" aria-expanded="false" class="accordion-button collapsed">
          Show danger zone
        </button>
      </h2>
      <div class="accordion-collapse collapse" style="">
        <div class="accordion-body" style="background: red;">
          <p>
            <button type="button" class="btn btn-primary">REMOVE PACKAGE AND ALL ITS DATA</button>
          </p>
        </div>
      </div>
    </div>
    

    It's the <button> element within the <h2> that gets the background-colour applied. It uses the selector .accordion-button when collapsed and .accordion-button:not(.collapsed) when expanded. If you make you CSS selectors to apply the red and light red background more specific they will override the defaults.

    As you have already added the class bg-red-500 to the <Accordion.Header> element, you can define the following CSS to override the defaults:

    .bg-red-500 .accordion-button:not(.collapsed) {
      background-color: rgb(255, 186, 186);
    }
    
    .bg-red-500 .accordion-button.collapsed {
      background-color: rgb(255, 0, 0);
    }
    

    This will give it a red header when collapsed, and a light red header when expanded. Please see this CodeSandbox for a working demo