React router dom set active class to the NavLink - reactjs

I am using React-router-dom for navigation
Routes.js
<Router>
<Switch>
<Route path="/" exact component={HomePage} activeClassName="routeActive"/>
<Route path="/login" exact component={Login} activeClassName="routeActive"/>
<Route path="/category/veg" exact component={Veg} activeClassName="routeActive"/>
<Route path="/category/non-veg" exact component={NonVeg} activeClassName="routeActive"/>
</Switch>
</Router>
then in my Navbar component i have
<div className="leftNavItems">
<ul className="navItemsUL">
<li className="navItemsLI">
<NavLink to="/" exact className="linkText" activeClassName="routeActive">
Home
</NavLink>
</li>
<li className="navItemsLI">
<NavLink to="/login" exact className="linkText" activeClassName="routeActive">
About us
</NavLink>
</li>
<div className="dropdown">
{console.log(props)}
{props.location}
<span className={` linkText`}>Categories </span>
<i className="fas fa-caret-down downIcon" />
<div className="dropdownContent">
<ul className="dropdownContentUL">
<li className="dropdownContentLI">
<Link to="/category/:veg" className="dropdownLinkText">
Veg
</Link>
</li>
<li className="dropdownContentLI">
<Link to="/category/:non-veg" className="dropdownLinkText">
Non Veg
</Link>
</li>
</ul>
</div>
</div>
</ul>
</div>
so as u can see i have used "activeClassName" for the Navlink to set className and then change its color if it is active but there is a case where i have a label "Category" which has a dropdown menu that contains for "veg" and "non-veg", so what i want is also need to change the color of "Category" label when the user is in either /category/veg or /caegory/:non-veg as it is Navbar Component console.log(props.location) is undefined over here bacause it is not insise i suppose. Any other way around here >

first, about console.log(props.location) turns to undefined, are you sure you wrapped the component with withRouter? also if it is a function component you can use the hook let location = useLocation()
second, you can control the class name manually like
<span className={`${props.location.pathname.split('/').includes('category') ? 'routeActive' : 'linkText' }`}>Categories </span>

Related

react router not working on some pages on live site

my live site and my code
all my links would just fine on npm start but when I ran npm run build the routes for some pages stop working. /about doesn't work at all and if you are on the 404 page and navigate back the /projects page stops working as well.
You should use BrowserRouter to wrap all your Routes in your Nav component and use Link to render About component as follows.
For more info: https://reactrouter.com/web/guides/quick-start
import "./nav.css";
import {
BrowserRouter as Router,
Route,
Link,
Redirect,
} from "react-router-dom";
import LogoS from "../imgs/logo-sm.png";
import Logo1 from "../imgs/logo-01.png";
import Projects from "./project-list";
import Aub from "./projects/auburn";
import M3d from "./projects/m3d";
import Uroute from "./projects/uroute";
import Thesis from "./projects/thesis";
import About from "./about";
import ACNH from "./projects/acnh";
const Nav = () => {
return (
<Router>
<div>
<header className="navbar">
<div className="container">
<Link to="/projects">
<p className="mb-0 navbar-brand">
<img
alt="Trisha Dring"
className="image logo d-sm-none"
src={LogoS}
/>
<img
className="image logo d-none d-sm-block"
alt="Trisha Dring"
src={Logo1}
/>
</p>
</Link>
<ul className="nav">
<li className="nav-item">
<Link
to="/about"
className="nav-link active"
aria-current="page"
>
About
</Link>
</li>
<li className="nav-item">
<a className="nav-link" href="/">
Resume
</a>
</li>
<li className="nav-item">
<a
className="nav-link"
href="mailto:trisha.dring+website#gmail.com"
>
Contact
</a>
</li>
</ul>
</div>
</header>
<Route path="/projects" component={Projects} />
<Route path="/ACNH" component={ACNH} />
<Route path="/Auburn" component={Aub} />
<Route path="/about" component={About} />
<Route path="/M3D" component={M3d} />
<Route path="/Uroute" component={Uroute} />
<Route path="/FixHFA" component={Thesis} />
<Route exact path="/">
<Redirect to="/projects" />
</Route>
</div>
</Router>
);
};
export default Nav;
By the way, in your About component, use className instead of class as follows. Otherwise, it will give warnings.
<p className="explain">Hi. I'm Trisha</p>

I should refresh browser to render my component using Routes | ReactJS

I have a menu with some routes. I want to show the component that correspond to his route while clicking on the menu. The issue is that, on the click, it changes me the url on my browser but the component displayed doesn't change. I have to refresh manually the page to render the good component. But my aim is to display the good component on the click without refreshing the page.
Here is my Menu.js code :
<Router>
<Link to={'/'} className="nav-link" id="homeLink">
<div className="tableElement active" id="home">
<FontAwesomeIcon icon={ faHome } className="icon"/>
</div>
</Link>
<Link to={'/org'} className="nav-link" id="orgLink">
<div className="tableElement" id="organisation">
<FontAwesomeIcon icon={ faTasks } className="icon"/>
</div>
</Link>
<Link to={'/users'} className="nav-link" id="usersLink">
<div className="tableElement" id="user">
<FontAwesomeIcon icon={ faUsers } className="icon"/>
</div>
</Link>
</Router>
Here is my render method App.js code :
render() {
return (
<Router>
<div className="App">
<LeftMenu/>
<Switch>
<Route exact path='/' component={Home}/>
<Route path='/org'
render={ (routeProps) => ( <Organisations {...routeProps} /> ) }
/>
<Route path='/users'
render={ (routeProps) => ( <UserTable {...routeProps} /> ) }
/>
</Switch>
</Router>
);
}
Thanks for your help !
I resolved my issue, I just made a big mistake, my bad.
I just deleted <Router> tags that wrapped my code in Menu.js.
<Link to={'/'} className="nav-link" id="homeLink">
<div className="tableElement active" id="home">
<FontAwesomeIcon icon={ faHome } className="icon"/>
</div>
</Link>
<Link to={'/org'} className="nav-link" id="orgLink">
<div className="tableElement" id="organisation">
<FontAwesomeIcon icon={ faTasks } className="icon"/>
</div>
</Link>
<Link to={'/users'} className="nav-link" id="usersLink">
<div className="tableElement" id="user">
<FontAwesomeIcon icon={ faUsers } className="icon"/>
</div>
</Link>
I believed that <Link> tags should be wrapped by <Router> tags to work. So if you have the same issue, just check if you wrapped your <Link> tags by <Router> tags, and delete them.

How to use react router

I am building an application that has different pages and I was wondering how I would be able to restructure my routess i want to load login component on '/' and i have this.props.history.push("/homepage") on login page which open up the homepage on successful login i have a navbar in the homepage with different links would i address loading the components in the homepage when links are clicked and i want the navbar to stay only in the homepage and load component next to it.I am new to react.Whats the best solution to this kind of scenario.
navbar code
import React, { Component } from "react";
import jwt_decode from "jwt-decode";
import { Link, withRouter } from "react-router-dom";
class Navbar extends Component {
logOut(event) {
event.preventDefault();
localStorage.removeItem("usertoken");
this.props.history.push("/login");
}
render() {
return (
<ul style={navBarStyle} id="sidenav-1" className="sidenav sidenav-fixed">
<li>
<h1 className="center-align" style={{ fontSize: "30px" }}>
Hello
</h1>
</li>
<li>
<Link to="/profile">
<i style={linkStyle} className="material-icons ">
person
</i>
</Link>
</li>
<li>
<a href="https://twitter.com/MaterializeCSS" target="_blank">
<i style={linkStyle} className="material-icons ">
book
</i>
</a>
</li>
<li>
<Link to="/searchcourse">
<i style={linkStyle} className="material-icons">
search
</i>
</Link>
</li>
<li style={linkStyle}>
<a href="" onClick={this.logOut.bind(this)}>
<i style={linkStyles} className="fas fa-sign-out-alt" />
</a>
</li>
</ul>
);
}
}
homepage
class Homepage extends Component {
componentDidMount() {
document.title = "Dashboard";
}
render() {
return (
<div>
<Navbar />
<div className="container">
<div>
<h3>Dashboard</h3>
<hr />
</div>
<div className="col" />
</div>
</div>
);
}
}
this is my app.js
<BrowserRouter>
<Route path="/login" component={Login} />
<Route path="/register" component={Register} />
<Route path="/homepage" component={Homepage} />
<Route exact path="/profile" component={Profile} />
<Route exact path="/searchcourse" component={SearchHelper} />
<Route exact path="/item" component={CourseItem} />
</BrowserRouter>
You can use nested routes. Keep Homepage specific sub-routes inside Homepage component. That way route /homepage will open up Homepage Component.
Inside Homepage you can have Navbar and the child routes of homepage like :
/homepage/profile, /homepage/item etc.
Here is one article to dig deep: https://medium.com/#marxlow/simple-nested-routes-with-layouts-in-react-router-v4-59b8b63a1184

React-Router: How to render different components on different parts of the page with one route

I have 2 links in my sidebar, this will change the link to "inbox" and "contacts" my problem is that when the route changes, the content of the sidebar doesn't change and I need to reload the page to render the content of it.
the links on the sidebar will append an ID and it can render perfectly the for example, the contact that has that ID in the route.
class App extends Component {
render() {
return (
<Router>
<div>
<SidebarContainer/>
<Route exact path="/inbox/:id" component={MessageContainer}/>
<Route path="/contacts" component={ContactContainer}/>
<Route path="/test" component={Test}/>
</div>
</Router>
)
}
}
Here's what I tried in the Component
render() {
return (
<div>
<li className="padded-left">
<div>
<Link onClick={this._showInbox} to="/inbox" className="waves-effect waves-teal btn-flat">
<i className="material-icons">chat</i>
</Link>
<Link onClick={this._showContacts} to="/contacts" className="waves-effect waves-teal btn-flat">
<i className="material-icons">contacts</i>
</Link>
</div>
</li>
<li>
<Link to="/test" className="waves-effect waves-teal btn-flat">
<i className="material-icons">Test</i>
</Link>
</li>
<li>
<div className="divider">_</div>
</li>
<Route path="/inbox" component={ConversationContainer}/>
<Route path="/contacts" component={ContactsContainer}/>
</ul>
</div>
);
}
In this case, I won't render the SideBarContainer inside the Router. You have to take into account that, when you navigate, the only thing that will be triggered to be rendered is the component inside the Route. Your Sidebar will always stay the same unless you refresh the page (here, the whole App is triggered to be rendered again)
As you are expecting the SideBar to change given a specific Route, you should render it inside the components of <Route /> .

React router doesnt route when clicking on link

so i have a header component with a couple of links:
{
this.props.cats.map(x =>
<li className="nav-item" key={x.path}><Link className="nav-link" to={x.path}>{x.name}</Link></li>)
}
The code snippet above is what i use to render the links
Then in my index.js(root) i use <BrowserRouter/> and it encompasses the whole element.
My question is to do with the routing i have implemented.
<Header />
<Switch>
<Route exact path='/' component={(props) => <PostList cat='all' posts={this.props.posts} />} />
<Route exact path='/:category' component={(props) => {
console.log(props.match.url)
return <PostList cat='filter' posts={this.props} />
}} />
</Switch>
When i click on the link to take me to say path "/test" it should be picked up by the second Route element and every time it changes it should display the link, it doesn't. It will only change if i do a hard refresh.
Any idea on what i could be doing wrong?
Edit* included header component
<nav className="navbar navbar-expand-sm navbar-light bg-light mb-3">
<div className="container">
<Link className="navbar-brand" to='/'>Navbar</Link>
<button className="navbar-toggler" data-toggle="collapse" data-target="#navbarNav"><span className="navbar-toggler-icon"></span></button>
<div className="collapse navbar-collapse" id="navbarNav">
<ul className="ml-auto navbar-nav">
{
this.props.cats.map(x =>
<li className="nav-item" key={x.path}><Link className="nav-link" to={x.path}>{x.name}</Link></li>)
}
</ul>
</div>
</div>
</nav>
Link is now part of 'react-router-dom', make sure you have imported it from there ,if this doesn't solve your problem then try to wrap your component with withRouter

Resources