Search code examples
cssreactjsbootstrap-5react-bootstrap

How to change the active colour of the selected item in NavBarDropdown of react-bootstrap?


I am using the react-bootstrap NavdropDown component from here. I had used it properly but I am unable to set the custom background colour of the navdropdow-items when its in normal & active i.e. selected state .

Like I would like to change from blue to any other colour when option is selected as shown in image.enter image description here

how can I do so ? (even using css can also help if there's no inbuilt class/attribute for this in bootstrap).

Navbar.js

      <Navbar bg="dark" variant="dark">
        <Container>
          <Navbar.Brand href="/master">Hi {user.sub}</Navbar.Brand>
          <Nav className="me-auto">
            
            .
            .
            .
            .
            .
            .

            <NavDropdown drop="down-centered" menuVariant="dark"  title="3P-Verticals" id="navbarScrollingDropdown">
              {
                verticals_3p.map((item)=> {
                  return(
                    <NavDropdown.Item key={item.val}>
                      <Nav.Link onClick={()=>props.setTenantName(item.val)}>{item.label}</Nav.Link>
                    </NavDropdown.Item>
                  )
                })
              }  
            </NavDropdown>
            .
            .
            .
            .
            .
            .
          </Nav>
        </Container>
      </Navbar>

I tried this in App.css but its not working.

#navbarScrollingDropdown:active {
  font-weight: bold;
}

Solution

  • It's <NavDropdown> that has an ID of navbarScrollingDropdown whereas it's the <NavDropdown.Item> that becomes active when selected. Also with how react-boostrap renders the DOM you end up with the following HTML:

    <div menuvariant="dark" class="nav-item show dropdown">
      <a aria-haspopup="true" aria-expanded="true" id="navbarScrollingDropdown" href="#" class="dropdown-toggle nav-link" role="button">3P-Verticals</a>
      <div aria-labelledby="navbarScrollingDropdown" class="dropdown-menu show" style="margin: 0px;">
        <a href="#action/3.1" class="dropdown-item">Action</a>
        <a href="#action/3.2" class="dropdown-item">Another action</a>
        <a href="#action/3.3" class="dropdown-item active">Something</a>
        <div class="dropdown-divider" role="separator"></div>
        <a href="#action/3.4" class="dropdown-item">Separated link</a>
      </div>
    </div>
    

    so even if you used the CSS selector #navbarScrollingDropdown .active it wouldn't work as the popup menu div sits outside of the menu item element with the ID navbarScrollingDropdown.

    You could override the CSS selector that is used by Bootstrap:

    .dropdown-item.active,
    .dropdown-item:active {
      background-color: green !important;
    }
    

    Here's a working CodeSandbox demo.