how to navigate with navintems for react-bootstrap without refreshing the whole page
Using React-Bootstrap to Create Navigation Without Page Refresh
To navigate using NavItems
in React-Bootstrap without refreshing the whole page, you can use the react-router-dom
library to handle the routing. Here's an example of how to achieve this:
import React from 'react';
import { Nav, Navbar } from 'react-bootstrap';
import { Link, BrowserRouter as Router, Route, Switch } from 'react-router-dom';
function App() {
return (
<Router>
<Navbar bg="light" expand="lg">
<Navbar.Toggle aria-controls="basic-navbar-nav" />
<Navbar.Collapse id="basic-navbar-nav">
<Nav className="mr-auto">
<Nav.Link as={Link} to="/">Home</Nav.Link>
<Nav.Link as={Link} to="/about">About</Nav.Link>
<Nav.Link as={Link} to="/contact">Contact</Nav.Link>
</Nav>
</Navbar.Collapse>
</Navbar>
<Switch>
<Route exact path="/">
<Home />
</Route>
<Route path="/about">
<About />
</Route>
<Route path="/contact">
<Contact />
</Route>
</Switch>
</Router>
);
}
function Home() {
return <h2>Home</h2>;
}
function About() {
return <h2>About</h2>;
}
function Contact() {
return <h2>Contact</h2>;
}
export default App;
In this example, we use the Link
component from react-router-dom
instead of the regular anchor tag (<a>
) to create the navigation links. The BrowserRouter
component is used to wrap the entire application and provide the routing functionality. Inside the Switch
component, we define the routes for each navigation link using the Route
component.
By setting up the routes and using the Link
component for navigation, the page will update content dynamically without causing a full page refresh when the navigation links are clicked.