Search

React Bootstrap Navbar Example

post-title

Bootstrap is easy to create responsive website with less code. Bootstrap provides easy to add component with simple design.

In this tutorial article, I will show you how to add Bootstrap navbar in React application. Bootstrap provides different style and color navbar.

In React application we will install react-bootstrap package to use Boostrap navbar components. Run the npm command to install Bootstrap package.

npm install react-bootstrap bootstrap

Now you will need to add bootstrap CSS file in index.js file.

import "bootstrap/dist/css/bootstrap.min.css";

Now create BootstrapNavbar class at /src/BootstrapNavbar.js file. Add the code in file. You need to import all file which you want to add in navbar link.

import React from 'react'
import {
    BrowserRouter as Router,
    Switch,
    Route,
    useParams,
} from "react-router-dom";
import { Navbar, Nav, NavDropdown, Button } from 'react-bootstrap'
import Home from './Home';

class BootstrapNavbar extends React.Component {

    render(){
        return(
            <div>
                <div className="row">
                    <div className="col-md-12">
                        <Router>
                            <Navbar bg="dark" variant="dark" expand="lg" sticky="top">
                                <Navbar.Brand href="#home">Bootstrap Navbar</Navbar.Brand>
                                <Navbar.Toggle aria-controls="basic-navbar-nav" />
                                <Navbar.Collapse id="basic-navbar-nav">
                                    <Nav className="mr-auto">
                                        <Nav.Link href="/">Home</Nav.Link>
                                    </Nav>
                                </Navbar.Collapse>
                            </Navbar>
                            <br />
                            <Switch>
                                <Route exact path="/">
                                    <Home />
                                </Route>
                            </Switch>
                        </Router>
                    </div>
                </div>
            </div>
        )  
    }
}

export default BootstrapNavbar;

Now import BootstrapNavbar class to main layout component file.

import './App.css';
import BootstrapNavbar from './BootstrapNavbar.js';

function App() {
  return (
    <div className="App">
      <BootstrapNavbar></BootstrapNavbar>
      // ...
    </div>
  );
}

export default App;

That's it. This way you can import multiple segment to main layout so it remains clean.