Last updated: Apr 6, 2024
Reading time·2 min
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 a certain component is mounted.
I've written a detailed guide on how to change an element's style on hover.
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 and 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.
I've also written an article on how to remove the underline from a link.
You can learn more about the related topics by checking out the following tutorials: