Search code examples
reactjsreact-bootstrap

How can I style a react bootstrap NavDropdown title atrribute and the NavDropdown.Item Links inside?


      <NavDropdown title="Products">
            <NavDropdown.Item href="#">Meat Alternatives</NavDropdown.Item>
            <NavDropdown.Item href="#">Soy Products</NavDropdown.Item>
            <NavDropdown.Item href="#">Vegan Deserts</NavDropdown.Item>
            <NavDropdown.Divider />
            <NavDropdown.Item href="#">Production</NavDropdown.Item>
          </NavDropdown>

I am new to react-bootstrap and I want to style the nav dropdown menu with my own CSS. I have tried using CSS selectors by wrapping the whole thing with a div, giving it a class of .style-dropdown, and targeting the title atribute

  <div className='style-dropdown'>
          <NavDropdown title="Products">
            <NavDropdown.Item href="#">Meat Alternatives</NavDropdown.Item>
            <NavDropdown.Item href="#">Soy Products</NavDropdown.Item>
            <NavDropdown.Item href="#">Vegan Deserts</NavDropdown.Item>
            <NavDropdown.Divider />
            <NavDropdown.Item href="#">Production</NavDropdown.Item>
          </NavDropdown>
          </div>

My CSS: .style-dropdown[title] { color: palevioletred !important; }

I have tried searching google but could'nt find the answer. Can anyone please help me?


Solution

  • One method is to declare the style directly within the render() method of your component, and then apply that to your <NavDropdown>.

    render() {
        let styleDropdown = {
            color: palevioletred
        };
        return (
            <NavDropdown title="Products" style={styleDropdown}>
               ...
            </NavDropdown>
        )
    }
    

    If you're using CSS modules (and I'd definitely recommend you do), you can import your styles and directly apply the className to the element.

    import styles from "./nav.module.css";
    
    <NavDropdown className={styles.myTitleStyle}>
        ...
    </NavDropdown>
    

    EDIT: The NavDropdown title renders as an <a> element, so in your CSS, you'll want:

    .myTitleStyle a
    {
        color: palevioletred !important;
    }