Topic: React Router doesn't work?
0xcristianoff asked 6 years ago
Expected behavior When I click on the NavItem with link to a page, I should be redirected to that page
Actual behavior Nothing happens lol
Resources (screenshots, code snippets etc.) My index.js is like that:
import App from "./App";
import Aboutus from "./pages/About"
import { BrowserRouter, Route, Switch } from 'react-router-dom';
import registerServiceWorker from './registerServiceWorker';
ReactDOM.render( <BrowserRouter>
<Switch>
<Route path="/" component={App} exact />
<Route path="/About" component={Aboutus} exact />
</Switch>
</BrowserRouter>,
document.getElementById('root'));
My navbar.js
import React, { Component } from "react";
import {
MDBNavbar, MDBNavbarBrand, MDBNavbarNav, MDBNavItem, MDBNavLink, MDBNavbarToggler, MDBCollapse, MDBFormInline,
MDBDropdown, MDBDropdownToggle, MDBDropdownMenu, MDBDropdownItem, MDBBtn
} 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 (
<Router>
<MDBNavbar color="white" light expand="md">
<MDBNavbarBrand>
<strong>
<img src={require('./logo-transparent-7.png')} width='125rem' />
</strong>
</MDBNavbarBrand>
<MDBNavbarToggler onClick={this.toggleCollapse} />
<MDBCollapse id="navbarCollapse3" isOpen={this.state.isOpen} navbar>
<MDBNavbarNav left>
<MDBNavItem>
<MDBNavLink to="/">Home</MDBNavLink>
</MDBNavItem>
<MDBNavItem>
<MDBNavLink to="/About">About</MDBNavLink>
</MDBNavItem>
<MDBNavItem>
<MDBNavLink to="/Contact">Contact</MDBNavLink>
</MDBNavItem>
</MDBNavbarNav>
<MDBNavbarNav right>
<MDBBtn color="success">Donate</MDBBtn>
</MDBNavbarNav>
</MDBCollapse>
</MDBNavbar>
</Router>
);
}
}
export default NavbarPage;
Jakub Mandra staff premium answered 6 years ago
Hey @0xcristianoff,
It is because you have wrapped your whole app in BrowserRouter and then your NavPage too, so they collide.
Remove wrapping <Router>
from NavbarPage and all shall work good :)
@Iskandar the symptoms which you described fits, so maybe your problem is the same?
Best,
Jakub
FREE CONSULTATION
Hire our experts to build a dedicated project. We'll analyze your business requirements, for free.
Answered
- User: Free
- Premium support: No
- Technology: MDB React
- MDB Version: 4.11.1
- Device: Laptop
- Browser: Google Chrome
- OS: Windows
- Provided sample code: No
- Provided link: No
0xcristianoff commented 6 years ago
It seems that if I click "refresh" the page renders. How can I make MDBNavLink trigger the refresh? Shouldn't it do it automatically?
Anna Morawska staff commented 6 years ago
Hi there, does the URL address changes after clicking MDBNavLink?
aideiskandar commented 6 years ago
@Anna Morawska: Hi there, I'm also facing the same issue. Yes the URL address does after click the MDBNavLink but not the contents.