set color to Reactsrap Navlink

Vana picture Vana · Mar 9, 2018 · Viewed 15k times · Source

I would like to set color "white" to my react component (Navlink). Home and logs link are always dark :( The white color is never set. I use Reacstrap, Bootstap 4. I separate js with css Here my code :

Sidebar.js

import React from 'react';
import { NavLink as RouterNavLink } from 'react-router-dom';
import { Collapse, Navbar, NavbarToggler, NavbarBrand, Nav, NavItem, NavLink 
} from 'reactstrap';
import './Sidebar.css';

export default class Sidebar extends React.Component {
constructor(props) {
super(props);
this.toggleNavbar = this.toggleNavbar.bind(this);
this.state = {
  collapsed: true
};
}
toggleNavbar() {
this.setState({
  collapsed: !this.state.collapsed
});
}
render() {
return (
  <div className="sidebar">
     <Navbar color="faded" light>
      <NavbarToggler onClick={this.toggleNavbar} className="mr-2" />
      <NavbarBrand href="/" className="mr-auto"></NavbarBrand>
<Collapse isOpen={!this.state.collapsed} navbar>
        <Nav navbar>
          <NavItem>
            <NavLink tag={RouterNavLink} to="/"className="test">Home</NavLink>
          </NavItem>
          <NavItem>
            <NavLink tag={RouterNavLink} to="/logs">Logs</NavLink>
          </NavItem>
        </Nav>
      </Collapse>
    </Navbar>
  </div>
);
}
}

and Sidebar.css

.sidebar {
display: flex;
flex-direction: column;
background:  #29363d;
width: 200px;
height: 844px;
}
.test {
font-family: sans-serif;
color: #fff;
}

Answer

Ula picture Ula · Jun 28, 2018

There are two ways of doing it ( if someone else needs it ):

This page on NavLink shows both ways of doing it:

  1. Using className

Above page defines followings:

'className' should define default (not currently active) NavLink's style in CSS;

'activeClassName' defines active page's NavLink CSS style.

So in your code

<NavLink to="/" className="inactive" activeClassName="active" exact={true}>Dashboard</NavLink>

then in CSS ( it did not work for me in any other CSS file except _base.scss - so if it does not work try it in _base.scss)

.inactive {
    color: #fff;
    text-decoration: none;
}

.active {
    color: red;
    text-decoration: none;
  }

(Note: See for example this Codepen.IO example prepared by someone else)

  1. Using 'style' and 'activeStyle':

    <NavLink to="/" style={{color: 'white', textDecoration: 'none'}} activeStyle={{color: 'red', textDecoration: 'none'}}>Home</NavLink>
    

Hope it helps someone !