Change the color of a Link in React


Borislav Hadzhiev

Tue Apr 19 20222 min read

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:

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="" target="_blank"> </a> </div> </Router> ); }

change color of link

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 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="" target="_blank"> </a> </div> </Router> ); }

The code sample uses inline styles to change the color of a Link component an 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.

Use the search field on my Home Page to filter through my more than 1,000 articles.