How to hide collapsible Bootstrap 4 navbar on click in react.js - javascript

I have created this Navbar using boostsrap 4, but i want it to get collapse when i click on the link,
Any way to do this? Thanks.
please help me i'm stuck here.
import moon from '../Images/moon.ico'
import { NavLink } from 'react-router-dom'
const NavBar = () => {
return(
<nav className="navbar navbar-expand-lg navbar-dark bg-dark">
<NavLink to='/' className="navbar-brand"><img src={moon} alt="logo" className="logo-img"/></NavLink>
<button className="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarNav" aria-controls="navbarNav" aria-expanded="false" aria-label="Toggle navigation">
<span className="navbar-toggler-icon"></span>
</button>
<div className="collapse navbar-collapse" id="navbarNav">
<ul className="navbar-nav">
<li className="nav-item">
<NavLink to="/" className="nav-link">Home</NavLink>
</li>
<li className="nav-item">
<NavLink to="/about" className="nav-link">About</NavLink>
</li>
<li className="nav-item">
<NavLink to='/skill' className="nav-link">Skills</NavLink>
</li>
<li className="nav-item">
<NavLink to="/project" className="nav-link">Projects</NavLink>
</li>
</ul>
</div>
</nav>
)
}
export default NavBar```

Related

React limits the number of renders to prevent an infinite loop with too many re-renders

My Main Motto is to use the Dark mode feature. In this case i'm Taking a Prop from app.js and assigning it to a state pMode and i am trying to change the class of the navbar using the setPmode method which is used as Ternary in onclick of Input tag and i am getting error of
Error : Too many re-renders. React limits the number of renders to prevent an infinite loop.
import React,{useState} from 'react';
export default function Navbar(props) {
let [pMode,setPmode] = useState(props.Mode);
return (
<>
<nav className={`navbar navbar-expand-lg navbar-${pMode} bg-${pMode}`}>
<div className="container-fluid">
<a className="navbar-brand" href="/">Navbar</a>
<button className="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarNav" aria-controls="navbarNav" aria-expanded="false" aria-label="Toggle navigation">
<span className="navbar-toggler-icon"></span>
</button>
<div className="collapse navbar-collapse " id="navbarNav">
<ul className="navbar-nav mx-auto">
<li className="nav-item">
<a className="nav-link active" aria-current="page" href="/">Home</a>
</li>
<li className="nav-item">
<a className="nav-link" href="/">Features</a>
</li>
<li className="nav-item">
<a className="nav-link" href="/">Pricing</a>
</li>
</ul>
<div className="form-check form-switch">
<input className="form-check-input" onClick={pMode=== "light"? setPmode("dark") : setPmode("light")} type="checkbox" role="switch" id="flexSwitchCheckDefault" />
<label className="form-check-label" htmlFor="flexSwitchCheckDefault">{pMode} mode</label>
</div>
</div>
</div>
</nav>
</>
);
}
This arrow function help with Infinite re-rendering.
onClick={()=>pMode=== "light"? setPmode("dark") : setPmode("light")}
import React,{useState} from 'react';
export default function Navbar(props) {
let [pMode,setPmode] = useState(props.Mode);
return (
<>
<nav className={`navbar navbar-expand-lg navbar-${pMode} bg-${pMode}`}>
<div className="container-fluid">
<a className="navbar-brand" href="/">Navbar</a>
<button className="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarNav" aria-controls="navbarNav" aria-expanded="false" aria-label="Toggle navigation">
<span className="navbar-toggler-icon"></span>
</button>
<div className="collapse navbar-collapse " id="navbarNav">
<ul className="navbar-nav mx-auto">
<li className="nav-item">
<a className="nav-link active" aria-current="page" href="/">Home</a>
</li>
<li className="nav-item">
<a className="nav-link" href="/">Features</a>
</li>
<li className="nav-item">
<a className="nav-link" href="/">Pricing</a>
</li>
</ul>
<div className="form-check form-switch">
<input className="form-check-input" onClick={()=>pMode=== "light"? setPmode("dark") : setPmode("light")} type="checkbox" role="switch" id="flexSwitchCheckDefault" />
<label className="form-check-label" htmlFor="flexSwitchCheckDefault">{pMode} mode</label>
</div>
</div>
</div>
</nav>
</>
);
}
You need to slightly modify the onClick function
<input
className="form-check-input"
onClick={() => setPMode((prev) => prev === 'light' ? 'dark' : 'light')}
type="checkbox"
role="switch"
id="flexSwitchCheckDefault" />
The issue earlier was that your onClick was a function call instead of a function. So every time the component rendered, the function call was executed which caused a change in state and then a re render. Also when your new state depends on previous state, it is recommended to use a function to setState
onClick={()=>{pMode=== "light"? setPmode("dark") : setPmode("light")}}
If you want to execute code inside onclick, you should use the arrow function.

Logout button not changing to login button in react-firebase single page site

This code worked the first time for login, but then when i logged out, it successfully did so but instead of changing the logout button to login again, after refreshing the page it just removed my name and pfp from the top of the navbar with the logout button still there, what changes should i make here to make it work?
here's a picture of the page before logout
here's a picture of the page after logout and refresh
import { NavLink } from 'react-router-dom';
import { useSelector } from 'react-redux';
import { auth, signInWithGoogle } from '../Firebase';
const Navbar = () => {
// To get a state of addItems, use name of the file not the function
const state = useSelector((state) => state.addItem);
const logOut = async () => {
await auth.signOut().then(console.log("signed out."));
localStorage.clear(auth);
}
return (
<div>
<nav className="navbar navbar-expand-lg navbar-light bg-light py-3 shadow-sm">
<div className="container">
<NavLink className="navbar-brand fw-bold fs-4" to="/">DUST</NavLink>
<button className="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
<span className="navbar-toggler-icon"></span>
</button>
<div className="collapse navbar-collapse" id="navbarSupportedContent">
<ul className="navbar-nav mx-auto mb-2 mb-lg-0">
<li className="nav-item">
<NavLink className="nav-link active" aria-current="page" to="/">HOME</NavLink>
</li>
<li className="nav-item">
<NavLink className="nav-link" to="/products">PRODUCTS</NavLink>
</li>
<li className="nav-item">
<NavLink className="nav-link" to="/about">ABOUT</NavLink>
</li>
<li className="nav-item">
<NavLink className="nav-link" to="/contact">CONTACT</NavLink>
</li>
</ul>
<div className="buttons">
{localStorage.getItem("name") === "" ? (
<button className="btn btn-outline-dark ms-3" onClick={signInWithGoogle}>
<i className='fa fa-sign-in me-1'></i> LOGIN
</button>
) : (
<>
<div className='container'>
<NavLink to="/cart" className="btn btn-outline-dark ms-2 me-5">
<i className='fa fa-shopping-cart me-1'></i>
{state?.length}
</NavLink>
<h4 className="lead">{localStorage.getItem("name")}</h4>
<img src={localStorage.getItem("profilePic")} alt="Profile" className='img-fluid img-responsive rounded-circle ms-2' style={{ height:50, width:50 }} />
<button className="btn btn-outline-dark ms-5" onClick={logOut}> {/*localstorage clear*/}
<i className='fa fa-sign-out me-1'></i> LOGOUT
</button>
</div>
</>
)
}
</div>
</div>
</div>
</nav>
</div>
);
}
export default Navbar;
The localStorage.getItem("test") === "" will always be false because if the key doesn't exist then getItem() returns null. Try:
// without === ""
localStorage.getItem("name") ? (...) : (...)
You can however read user's name directly from Firebase authentication:
auth.currentUser?.displayName

Bootstrap in React.js - Navbar collapse doesn't work

I am facing the problem, when trying to use the navbar colapse button from Bootstrap, it doesn't work.
I think it has something to do with my page loading the jQuery library or something, though I don't understand. In node modules I found all bootstrap js files. I am also importing them in my index.js file.
Here is my code.
import React, {Component} from 'react';
import AuthenticationService from '../service/AuthenticationService';
import { Sitemap } from '../settings/Sitemap';
class NavigationComponent extends Component {
render() {
return(
<nav className="navbar navbar-expand-lg navbar-light bg-light">
<div className="container">
Fit Vision
<button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#toggler" aria-controls="toggler" aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse" id="toggler">
<ul className="navbar-nav">
{Sitemap.map((item, index) => {
return (
<li className="nav-item" key={index}>
<a className="nav-link" href={item.url}>{item.title}</a>
</li>
)
})}
</ul>
<ul className="navbar-nav justify-content-end">
<li className="nav-item">
<a className="nav-link" href="/login">Login</a>
</li>
<li className="nav-item">
<a className="nav-link" href="/" onClick={AuthenticationService.logout}>Logout</a>
</li>
</ul>
</div>
</div>
</nav>
)
}
}
export default NavigationComponent;
My index.js
import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import reportWebVitals from './reportWebVitals';
import 'bootstrap/dist/css/bootstrap.css';
import 'bootstrap/dist/js/bootstrap.bundle.min';
ReactDOM.render(
<React.StrictMode>
<App />
</React.StrictMode>,
document.getElementById('root')
);
reportWebVitals();
first of all, you have some classes that should be converted into className.
Second, you should know that bootstrap depends on jquery.
Please npm install jquery in the directory.
Now looking at the index.js file you should next files imported :
import 'bootstrap/dist/css/bootstrap.css';
import 'bootstrap/dist/js/bootstrap.bundle';
Your Navigation.js should look like this:
import React, {Component} from 'react';
import AuthenticationService from '../service/AuthenticationService';
import { Sitemap } from '../settings/Sitemap';
class NavigationComponent extends Component {
render() {
return(
<nav className="navbar navbar-expand-lg navbar-light bg-light">
<div className="container">
Fit Vision
<button className="navbar-toggler" type="button" data-toggle="collapse" data-target="#toggler" aria-controls="toggler" aria-expanded="false" aria-label="Toggle navigation">
<span className="navbar-toggler-icon"></span>
</button>
<div className="collapse navbar-collapse" id="toggler">
<ul className="navbar-nav">
{Sitemap.map((item, index) => {
return (
<li className="nav-item" key={index}>
<a className="nav-link" href={item.url}>{item.title}</a>
</li>
)
})}
</ul>
<ul className="navbar-nav justify-content-end">
<li className="nav-item">
<a className="nav-link" href="/login">Login</a>
</li>
<li className="nav-item">
<a className="nav-link" href="/" onClick={AuthenticationService.logout}>Logout</a>
</li>
</ul>
</div>
</div>
</nav>
)
}
}
export default NavigationComponent;
Also i would suggest to use function components , it should be a simple change :
import React from 'react';
import AuthenticationService from '../service/AuthenticationService';
import { Sitemap } from '../settings/Sitemap';
function NavigationComponent() {
return(
<nav className="navbar navbar-expand-lg navbar-light bg-light">
<div className="container">
Fit Vision
<button className="navbar-toggler" type="button" data-toggle="collapse" data-target="#toggler" aria-controls="toggler" aria-expanded="false" aria-label="Toggle navigation">
<span className="navbar-toggler-icon"></span>
</button>
<div className="collapse navbar-collapse" id="toggler">
<ul className="navbar-nav">
{Sitemap.map((item, index) => {
return (
<li className="nav-item" key={index}>
<a className="nav-link" href={item.url}>{item.title}</a>
</li>
)
})}
</ul>
<ul className="navbar-nav justify-content-end">
<li className="nav-item">
<a className="nav-link" href="/login">Login</a>
</li>
<li className="nav-item">
<a className="nav-link" href="/" onClick={AuthenticationService.logout}>Logout</a>
</li>
</ul>
</div>
</div>
</nav>
)
}
export default NavigationComponent;

'/' home nav item color is showing active even changing of NavLink in ReactJs

I'm using NavLink to show the for Routing and showing item active of selected items.By default the home item is showing as active even I switched to other item. Except home others are working as expected.
Help me to sort out this bug.
In the following figure, Home (in red color) as active color even I switched to contact
My code as follows:
import React from "react";
import { withRouter, NavLink } from "react-router-dom";
class TopNav extends React.Component {
render() {
return (
<div>
<nav className="navbar navbar-expand-lg navbar-bg">
{/* <img className="logo-image" src={logo} alt="logo" /> */} Logo
<button
className="navbar-toggler"
type="button"
data-toggle="collapse"
data-target="#navbarNav"
aria-controls="navbarNav"
aria-expanded="false"
aria-label="Toggle navigation"
>
<span className="navbar-toggler-icon"></span>
</button>
<div className="collapse navbar-collapse" id="navbarNav">
<ul className="navbar-nav ml-auto ">
<li className="nav-item">
<NavLink
className="nav-link menu-list "
activeClassName="active"
to="/"
>
Home
</NavLink>
</li>
<li className="nav-item ">
<NavLink
className="nav-link menu-list"
activeClassName="active"
to="about"
>
About
</NavLink>
</li>
<li className="nav-item">
<NavLink className="nav-link menu-list" activeClassName="active" to="contact">
Contact
</NavLink>
</li>
</ul>
</div>
</nav>
</div>
);
}
}
export default withRouter(TopNav);
You can also specify the exact prop on NavLink components. The to prop (and path prop for Route components) match by path prefix, and "/" is a prefix for all routes.
exact: bool
When true, the active class/style will only be applied if
the location is matched exactly.
<NavLink
className="nav-link menu-list "
activeClassName="active"
to="/"
exact // <-- specify exact match!
>
Home
</NavLink>

add icon to header navBar (I am not getting that how to add icon on the most left in my NavBar)

add icon to header navBar
I am not getting that how to add icon on the most left in my NavBar.
This is a custom class of NavBar.js. I want an icon in this bar on the most left.
I have added the buttons with link and they are in the center of the nav bar
i want the icon .png to be appear to the most left in the navBar
Kindly help!!
import React, { Component } from 'react'
import { Link, withRouter } from 'react-router-dom'
class Navbar extends Component {
logOut (e) {
e.preventDefault()
localStorage.removeItem('usertoken')
this.props.history.push(`/`)
}
render () {
const loginRegLink = (
<ul className="navbar-nav">
<li className="nav-item">
<Link to="/login" className="nav-link">
Login
</Link>
</li>
<li className="nav-item">
<Link to="/my" className="nav-link">
my
</Link>
</li>
<li className="nav-item">
<Link to="/register" className="nav-link">
Register
</Link>
</li>
</ul>
)
const userLink = (
<ul className="navbar-nav">
<li className="nav-item">
<Link to="/profile" className="nav-link">
User
</Link>
</li>
<li className="nav-item">
<a href="#" onClick={this.logOut.bind(this)} className="nav-link">
Logout
</a>
</li>
</ul>
)
return (
<nav className="navbar navbar-expand-lg navbar-dark bg-dark rounded">
<button className="navbar-toggler"
type="button"
data-toggle="collapse"
data-target="#navbar1"
aria-controls="navbar1"
aria-expanded="false"
aria-label="Toggle navigation">
<span className="navbar-toggler-icon"></span>
</button>
<div className="collapse navbar-collapse justify-content-md-center"
id="navbar1">
<ul className="navbar-nav">
<li className="nav-item">
<Link to="/" className="nav-link">
Home
</Link>
</li>
</ul>
{localStorage.usertoken ? userLink : loginRegLink}
</div>
</nav>
)
}
}
export default withRouter(Navbar)
```
App.js
import React, { Component } from "react";
import { Link, withRouter } from "react-router-dom";
class Navbar extends Component {
logOut(e) {
e.preventDefault();
localStorage.removeItem("usertoken");
this.props.history.push(`/`);
}
render() {
const loginRegLink = (
<ul className="navbar-nav">
<li className="nav-item">
<Link to="/login" className="nav-link">
Login
</Link>
</li>
<li className="nav-item">
<Link to="/profile" className="nav-link">
Profile
</Link>
</li>
<li className="nav-item">
<Link to="/register" className="nav-link">
Register
</Link>
</li>
</ul>
);
const userLink = (
<ul className="navbar-nav">
<li className="nav-item">
<Link to="/profile" className="nav-link">
User
</Link>
</li>
<li className="nav-item">
<Link onClick={this.logOut.bind(this)} className="nav-link">
Logout
</Link>
</li>
{/* Dropdown */}
<li className="nav-item dropdown">
<Link
className="nav-link dropdown-toggle"
id="navbardrop"
data-toggle="dropdown"
>
Dropdown link
</Link>
<div className="dropdown-menu">
<Link className="dropdown-item" href="#">
Link 1
</Link>
<Link className="dropdown-item" href="#">
Link 2
</Link>
<Link className="dropdown-item" href="#">
Link 3
</Link>
</div>
</li>
</ul>
);
return (
<nav className="navbar navbar-expand-md bg-dark navbar-dark">
<Link className="navbar-brand">
<img
src="https://via.placeholder.com/50"
alt="Logo"
className="img-thumbnail"
/>
</Link>
<button
className="navbar-toggler"
type="button"
data-toggle="collapse"
data-target="#collapsibleNavbar"
>
<span className="navbar-toggler-icon" />
</button>
<div
className="collapse navbar-collapse justify-content-md-center"
id="collapsibleNavbar"
>
{localStorage.usertoken ? userLink : loginRegLink}
</div>
</nav>
);
}
}
export default withRouter(Navbar);
index.js
import React from "react";
import { render } from "react-dom";
import { BrowserRouter as Router, Route } from "react-router-dom";
import Nav from "./App";
const App = props => (
<Router>
<div>
<Nav />
<Route exact path="/" />
</div>
</Router>
);
render(<App />, document.getElementById("root"));
Hi please check the Link for add icon in most left.

Categories

Resources