Change the color of a Link in React

avatar
Borislav Hadzhiev

Last updated: Apr 6, 2024
2 min

banner

# Change the color of a Link in React

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.

App.css
a { color: green; } a:hover { color: red; }

And here is how you would import your CSS file to apply the styles.

App.js
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> ); }

change color of link

The code for this article is available on GitHub

The styles are applied to both Link components and anchor elements because under the hood, the Link component is really just an <a> tag.

This approach also works when using third-party libraries that provide wrapper components for links. As long as the library uses an 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.

# Change the color of a Link in React using inline styles

If you don't have to use pseudo-classes like hover, you can also use an inline style to change a Link's color.

App.js
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> ); }

change color of link using inline styles

The code for this article is available on GitHub

The code sample uses inline styles to change the color of a Link component and an a tag.

The first set of curly braces in the inline style marks the beginning of an expression, and the second set of curly braces is the object containing styles and values.

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.

# Additional Resources

You can learn more about the related topics by checking out the following tutorials:

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.