Search code examples
reactjsreactstrap

ReactStrap NavLinks are broken when rendered via a component


The following code renders my NavLinks properly in my ReactStrap DropdownMenu:

<!-- RENDERS CORRECTLY -->

<Nav className="ml-auto" navbar>
    <UncontrolledDropdown nav inNavbar>
        <DropdownToggle nav caret> A dropdown menu </DropdownToggle>
          <DropdownMenu>
            <NavLink className="dropdown-item" to=“/url1”> item 1 </NavLink>
            <NavLink className="dropdown-item" to=“/url2”> item 2 </NavLink>
          </DropdownMenu>
     </UncontrolledDropdown>
</Nav>

But if I move the DropdownMenu into a separate component as follows, returning exactly the same JSX, the css is screwy and the resulting a elements have "to" attributes instead of "href" attributes, so the links don't work.

<!-- BREAKS -->

<Nav className="ml-auto" navbar>
    <UncontrolledDropdown nav inNavbar>
        <DropdownToggle nav caret> A dropdown menu </DropdownToggle>
          <DropdownMenuComponent/>
     </UncontrolledDropdown>
</Nav>

...

class DropdownMenuComponent extends Component {    
    render() {
        return (
            <DropdownMenu>
               <NavLink className="dropdown-item" to=“/url1”> item 1 </NavLink>
            <NavLink className="dropdown-item" to=“/url2”> item 2 </NavLink>
            </DropdownMenu>
        );
    }
}

Any ideas how I can fix this? It's disconcerting to use ReactStrap if I can't count on basic nesting of components.


Solution

  • You have to wrap the links in the <DropdownItem> component and then they'll render correctly.

    I put together a working sandbox here

    import React from "react";
    import ReactDOM from "react-dom";
    import {
      Nav,
      UncontrolledDropdown,
      DropdownToggle,
      DropdownMenu,
      DropdownItem,
      NavLink
    } from "reactstrap";
    import "bootstrap-css-only";
    
    
    const DropdownComponent = () => (
      <DropdownMenu>
        <DropdownItem>
          <NavLink className="dropdown-item" to="/url1">
            item 1
          </NavLink>
        </DropdownItem>
        <DropdownItem>
          <NavLink className="dropdown-item" to="/url2">
            item 2
          </NavLink>
        </DropdownItem>
      </DropdownMenu>
    );
    
    const App = () => {
      return (
        <Nav className="ml-auto" navbar>
          <UncontrolledDropdown nav inNavbar>
            <DropdownToggle nav caret>
              A dropdown menu
            </DropdownToggle>
            <DropdownComponent />
          </UncontrolledDropdown>
        </Nav>
      );
    };
    
    const rootElement = document.getElementById("root");
    ReactDOM.render(<App />, rootElement);