Reputation: 267
I want to get NavLink to apply CSS styles in react. But I can not target NavLink.
Code:
.navUl li NavLink {
display: block;
color: white;
text-align: center;
padding: 14px 16px;
text-decoration: none;
}
<nav className='myNavbar'>
<ul className='navUl'>
<li>
<NavLink activeClassName='active' exact to="/">Function</NavLink>
</li>
<li>
<NavLink activeClassName='active' exact to="/class">Class</NavLink>
</li>
<li>
<NavLink activeClassName='active' exact to="/users">Logout</NavLink>
</li>
</ul>
</nav>
How do I target the NavLink component with css?
Upvotes: 2
Views: 6164
Reputation: 20821
Assuming NavLink
passes props to underlying JSX, you should be able to pass a className
prop to the NavLink components which will be rendered as the class
attribute in the html that react renders.
Then you can target it with a regular css class selector.
// styles.css
.navUl li .navLink {
display: block;
color: white;
text-align: center;
padding: 14px 16px;
text-decoration: none;
}
// App.js
import "./styles.css";
export default function App() {
return (
<nav className="myNavbar">
<ul className="navUl">
<li>
<NavLink className="navLink" activeClassName="active" exact to="/">
Function
</NavLink>
</li>
<li>
<NavLink
className="navLink"
activeClassName="active"
exact
to="/class"
>
Class
</NavLink>
</li>
<li>
<NavLink
className="navLink"
activeClassName="active"
exact
to="/users"
>
Logout
</NavLink>
</li>
</ul>
</nav>
);
}
Upvotes: 1
Reputation: 1291
If you are using styled-components
then
import styled from 'styled-components';
/* The First Method */
export const NavLink = styled.a`
// your style goes here
`;
/* The Other Method */
const NavLink = styled.a`
// your style goes here
`;
export default NavLink;
And if you are using functional-components
then
export default function NavLink(...props) {
return <a href="" {...props}> </a>
}
...props
will let you any property you want like
<a href="" style="" className="" ...andMuchMore> </a>
And if just jsx
then it will look something like this
<nav class="navbar">
<a href="/home" className="nav-link"> Home </a>
<a href="/about" className="nav-link"> About </a>
</nav>
I don't use class components
so often so I don't quite know about it.
Upvotes: 1
Reputation: 884
NavLink
change to a
in html
So your class should be like this
.navUl li a{
...
}
Upvotes: 1