Borislav Hadzhiev
Tue Apr 19 2022·2 min read
Photo by Soroush Karimi
Use a css file to change the color of a link in React. You can define styles
that apply to anchor elements and import the css
file in your component for
the styles to take effect.
Your css
file could look something like this:
a { color: green; } a:hover { color: red; }
And here is how you would import your css
file to apply the styles.
import {BrowserRouter as Router, Link} from 'react-router-dom'; import './App.css'; export default function App() { return ( <Router> <div> <Link to="/">Home</Link> <br /> <br /> <a href="google.com" target="_blank"> Google.com </a> </div> </Router> ); }
The styles are applied to both Link
components and anchor elements because
under the hood the Link
component is really just an <a>
tag.
a
tag, the link's color will get set.It's a best practice to import your global css
files in your index.js
file
because then they wouldn't only get loaded when certain component is mounted.
If you don't have to use pseudo-classes like hover, you can also use an inline style to change a Link's color.
import {BrowserRouter as Router, Link} from 'react-router-dom'; export default function App() { return ( <Router> <div> <Link style={{color: 'green'}} to="/"> Home </Link> <br /> <br /> <a style={{color: 'red'}} href="google.com" target="_blank"> Google.com </a> </div> </Router> ); }
The code sample uses
inline styles to change the
color of a Link component an an a
tag.
Make sure to set the color
property on the Link element and not on its
children.
If you use an inline style for the color
property, you can't update the hover
pseudo-class for the same property in your global css
file, because inline
styles have higher precedence.