Search code examples
reactjsreact-bootstrap

How to add a Glyphicon to NavDropdown in ReactBootstrap


I'm trying to add a glyphicon to a NavDropdown in React Bootstrap. I know that you can add it to a normal Dropdown like this, as explained in the documentation.

<Dropdown id="dropdown-custom-1">
  <Dropdown.Toggle>
    <Glyphicon glyph="star" />
    Pow! Zoom!
  </Dropdown.Toggle>
  <Dropdown.Menu >
    <MenuItem eventKey="1">Action</MenuItem>
    <MenuItem eventKey="2">Another action</MenuItem>
  </Dropdown.Menu>
</Dropdown>

What I've tried:

1. Does not work:

    <NavDropdown eventKey={3} id="basic-nav-dropdown">
       <NavDropdown.Toggle>
       <Glyphicon glyph="star" />
       Pow! Zoom!
       </NavDropdown.Toggle>
       <MenuItem eventKey={3.1}>Action</MenuItem>
       <MenuItem eventKey={3.2}>Another action</MenuItem>
    </NavDropdown>

2. Does not work:

    <NavDropdown eventKey={3} title={<Glyphicon glyph="star" /> Dropdown} id="basic-nav-dropdown">
       <MenuItem eventKey={3.1}>Action</MenuItem>
       <MenuItem eventKey={3.2}>Another action</MenuItem>
    </NavDropdown>

3. Does work but the caret is not aligned with the text and it appears in a new line:

    <NavDropdown eventKey={3} title={<div><Glyphicon glyph="star" /> Dropdown </div>} id="basic-nav-dropdown">
       <MenuItem eventKey={3.1}>Action</MenuItem>
       <MenuItem eventKey={3.2}>Another action</MenuItem>
    </NavDropdown>

Solution

  • You can try to pass a title through the <Glyphicon /> component like this:

     render() {
         const navDropdownTitle = (<Glyphicon glyph="star"> Dropdown </Glyphicon>);
         return (
           <NavDropdown title={navDropdownTitle} eventKey={3} id="basic-nav-dropdown">
              <MenuItem eventKey={3.1}>Action</MenuItem>
              <MenuItem eventKey={3.2}>Another action</MenuItem>
           </NavDropdown>
          )
    }
    

    (Update) Or we can use your approach but with small fix for div style. The font style does not break down in this case.

     <NavDropdown eventKey={3} title={<div style={{display: "inline-block"}}><Glyphicon glyph="star" /> Dropdown </div>} id="basic-nav-dropdown">
       <MenuItem eventKey={3.1}>Action</MenuItem>
       <MenuItem eventKey={3.2}>Another action</MenuItem>
    </NavDropdown>
    

    And you probably will need to disable text-decoration: underline style to make drop-down look better. For example with this css-rule:

    a.dropdown-toggle {
        text-decoration: none;
    }