Rakonjac
Rakonjac

Reputation: 87

ReactJS Router activeClassName issue

I'm stuck with this problem. Help Help ! I'm using Router in npx create-react-app. I want to apply activeClassName to my NavLinks, but for some reason it does not work. Can someone please explain to me, why activeClassName is not applyed to NavLink when i click on it. Here is the code.

Nav component:

import React from 'react'
import {  NavLink } from 'react-router-dom'
import './nav.css'

const nav =()=>{
return(
    <nav className='Nav'>
      <ul>
        <li><NavLink className="link" to='/' activeClassName="active">Home</NavLink></li>
        <li><NavLink className="link" to='/work' exact activeClassName="active">Work</NavLink></li>
        <li><NavLink className="link" to='/about' exact activeClassName="active">About</NavLink></li>
        <li><NavLink className="link" to='/skills' exact activeClassName="active">Skills</NavLink></li>
      </ul>
    </nav>
  )
 }

 export default nav;

App component:

import React, { Component } from 'react';
import './App.css';
import { Route, Switch } from 'react-router-dom'

import Nav from './nav'
import Home from './home'
import About from './about'
import Work from './work'
import Skills from './skills'

class App extends Component {

   render(){

   console.log(this.props)
     return (
       <div className="App">
         <Nav/>
         <div>
           <Switch>
             <Route path='/' exact><Home/></Route>
             <Route path='/work' exact><Work/></Route>
             <Route path='/about' exact><About/></Route>
             <Route path='/skills' exact><Skills/></Route>
           </Switch>
         </div>
       </div>
     );
   }
 }

 export default App;

Index.js

import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import * as serviceWorker from './serviceWorker';
import { BrowserRouter } from 'react-router-dom'

ReactDOM.render(
  <BrowserRouter>
    <App />
  </BrowserRouter>,
 document.getElementById('root')
);

serviceWorker.unregister();

Upvotes: 0

Views: 956

Answers (2)

hotpink
hotpink

Reputation: 3226

If the style is not applied at all, then I reckon there is something not quite right in your CSS. Looking at your code I would expect the style to be applied to your first NavLink with the location '/' and then every subsequent NavLink when you click on it. To prevent that you would have to add exact to the one linking to Home

Writing out activeClassName="active" is also not required as 'active' is the default given class

Upvotes: 2

Friday Ameh
Friday Ameh

Reputation: 1684

Add important to your active class like so. other styles might be overriding it. Also, ensure your CSS file is in the current directory

.active{
color:red!important
}

Upvotes: 0

Related Questions