Home > OS >  bootstrap nav link is not working in reactjs
bootstrap nav link is not working in reactjs

Time:10-11

I'm new here also newbie on ReactJS.

Here I created a navbar using bootstrap navbar component in Reactjs.

<Navbar collapseOnSelect expand="lg">
  <Container>
    <Navbar.Brand to={"/"}>Rental</Navbar.Brand>
    <Navbar.Toggle aria-controls="responsive-navbar-nav" />
    <Navbar.Collapse id="responsive-navbar-nav">

    <Nav>
      <Nav.Link to="/" >
         <FontAwesomeIcon 
          icon={faHome} 
       /> Home
     </Nav.Link>
     <Nav.Link to="/login" >
        <FontAwesomeIcon 
        icon={faUser} 
        /> Login/ Registration
     </Nav.Link>
  </Nav>
  </Navbar.Collapse>
 </Container>
</Navbar>

When I go Browser and Check It shows like this:

<a to="/" role="button" class="nav-link" tabindex="0">Home</a>

and the link won't working.

How to fix it?

CodePudding user response:

It looks like you're rendering react-bootstrap's Nav.Link instead of react-router's Link component, so the router is not picking up your route changes.

So importing Link from react router and using it should fix the issue.

import { Link } from 'react-router-dom';

<Nav.Link as={Link} to="/" >
         <FontAwesomeIcon 
          icon={faHome} 
       /> Home

CodePudding user response:

Wrap your code in a Router, make sure that you're doing that inside App or in ReactDOM.render:

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

ReactDOM.render(
  <BrowserRouter>
    <App />
  </BrowserRouter>, 
  rootElement
  );

You're rendering react-bootstrap's Nav.Link instead of react-router's Link component, so the router is not picking up your route changes.

react-bootstrap provides a render prop in most of its components to specify which component or element we want to render if we don't want the default.

Try to make these changes!

import { Switch, Route, Link } from 'react-router-dom';
<Navbar.Brand as={Link} to="/" >Rental</Navbar.Brand>
<Nav.Link as={Link} to="/" >
    <FontAwesomeIcon icon={faHome}/>
        Home
</Nav.Link>
<Nav.Link as={Link} to="/login" >
    <FontAwesomeIcon icon={faUser}/> 
        Login/ Registration
</Nav.Link>
  • Related