How to change the color of a Link in React

Change the color of a Link in React

The topic of this article will be how to change the color of a Link in React in some way, for example, using the external style or inline style method. Let’s go into detail now.

Change the color of a Link in React

In HTML, the pair of tags to redirect is <a></a> tag. In react, we will use the <Link></Link> tag pair imported from React-Router.

<Link to="/about">About</Link>

The to attribute, like the href attribute in the <a> tag, will be the path to where this tag navigates. 

So how can we change from the default color of the Link tag to a custom color of our own? Let’s see how to do it below.

Using the external style method

This way, we will add css to the App.css file so that the program can recognize the css we apply to the website. In the file that needs css, we will add “import ‘./App.css’;” like the following code.

import {BrowserRouter as Router, Link} from 'react-router-dom';
 
import './App.css';
 
export default function App() {
  return (
    <Router>
      <>
        <h2>Change the color of a Link in React | LearnShareIT</h2>
        <hr/>
        <Link to="/">Home</Link>
        <br/>
        <Link to="/about">About</Link>
      </>
    </Router>
  );
}
a {
  color: white;
}
a:hover {
  color: green;
}

Output:

Because react-router-dom’s Link tag is essentially a built-in function of this library, inside it is a tag that developers write to add functionality. So we need to css into the <a> tag that every <a> tag on the whole page will be applied attributes, including the Link tag.

Using the inline style method

This way, we will write inline style for each Link tag that we need css different from its default using the style attribute. Take a look at the following example.

Code:

import { BrowserRouter as Router, Link } from "react-router-dom";
 
export default function App() {
  return (
    <Router>
      <>
        <h2>Change the color of a Link in React | LearnShareIT</h2>
        <hr />
        <Link to="/" style={{ color: "green" }}>
          Home
        </Link>
        <br />
        <Link to="/about" style={{ color: "green" }}>
          About
        </Link>
      </>
    </Router>
  );
}

However, according to my understanding, it will be very limited in adding hover to the Link tag because the inline style is not supported. So we have to add javascript code to do this, which is quite lengthy. In the example above, I just changed the default color of the Link tag to green. Wish you success with the methods mentioned in the article.

Summary

In summary, you have learned how to change the color of a Link in React in two ways, but as I mentioned in the article, you should use external styles because the other way has many limitations. Good lucks for you!

Maybe you are interested:

Leave a Reply

Your email address will not be published. Required fields are marked *