Topic: MDBNavLink causing error when used with connected-react-router

RyanMDBST free asked 5 years ago


Hello,

So I have recently purchased the pro version of the mdbreact library and I'm suddenly receiving the following error when attempting to use the MDBNavLink component:

Invariant failed: You should not use <NavLink> outside a <Router>

My setup does contain a <Router> (in the form of <ConnectedRouter>) at the very top of my component heirarchy so I believe this to be an error. I should also mention that my code worked perfectly fine with the free version of mdbreact and the error only occured after upgrading to the pro version.

For the time being I have replaced the component with it's standard HTML version but obviously this isn't ideal.

Thanks for your help in advance,

Regards,

Ryan


Jakub Chmura staff answered 5 years ago


Hi,

I tried sample code from our documentation and I didn't achieve this error. If you want to use MDBNavLink you need to import:

 import { BrowserRouter as Router } from 'react-router-dom';

And wrap your navbar or links like in the example in our documentation.

Can you add Router as <BrowserRouter> like a wrapper for your file when you use <NavLink>?

Something like this:

import React, { Component } from "react";
import {
MDBNavbar, MDBNavbarBrand, MDBNavbarNav, MDBNavItem, MDBNavLink, MDBNavbarToggler, MDBCollapse, MDBFormInline,
MDBDropdown, MDBDropdownToggle, MDBDropdownMenu, MDBDropdownItem
} from "mdbreact";
import { BrowserRouter as Router } from 'react-router-dom';

class NavbarPage extends Component {
state = {
  isOpen: false
};

toggleCollapse = () => {
  this.setState({ isOpen: !this.state.isOpen });
}

render() {
  return (
    <BrowserRouter> //Here <-----------------
      <MDBNavbar color="indigo" dark expand="md">
        <MDBNavbarBrand>
          <strong className="white-text">Navbar</strong>
        </MDBNavbarBrand>
        <MDBNavbarToggler onClick={this.toggleCollapse} />
        <MDBCollapse id="navbarCollapse3" isOpen={this.state.isOpen} navbar>
          <MDBNavbarNav left>
            <MDBNavItem active>
              <MDBNavLink to="#!">Home</MDBNavLink>
            </MDBNavItem>
          </MDBNavbarNav>
        </MDBCollapse>
      </MDBNavbar>
    </BrowserRouter> //And here <-----------------
    );
  }
}

export default NavbarPage;

Thank you for reporting the error. I hope my solution will work.

Best Regards, Kuba



Please insert min. 20 characters.

FREE CONSULTATION

Hire our experts to build a dedicated project. We'll analyze your business requirements, for free.

Status

Answered

Specification of the issue

  • ForumUser: Free
  • Premium support: No
  • Technology: MDB React
  • MDB Version: 4.21.0
  • Device: N/A
  • Browser: N/A
  • OS: N/A
  • Provided sample code: No
  • Provided link: No