简体   繁体   中英

How to change a <a> tag color when I click on it and it doesn't change until I change my URL

What i'm trying to do is basically keep the color of an link when I click on it, hovering the navbar link makes it greyish, and when I click on it and while it stays on the URL i want to keep it a different color. I'm using react-router-dom for the Link component

         <nav>
          <ul className="nav-wrapper">
            <li>
              <Link className="link" to="/">
                Home
              </Link>
            </li>
            <li>
              <Link className="link" to="/gallery">
                Gallery
              </Link>
            </li>
            <li>
              <Link className="link" to="/about">
                About
              </Link>
            </li>
          </ul>
        </nav>

I don't really know what to use here, i don't know if I should use a useState to try and change it when I click on it or change it on CSS, any tips are appreciated.

( I didn't understand your question well so I did both) Ok! Try this to change an unvisited link (CSS) a:link { color: what color you want; } a:link { color: what color you want; }

Use this to change a visited link (CSS)' a:visited { color: what color you want; } a:visited { color: what color you want; }

Code example:

 a:active { color: green; } a:visited { color: purple; }
 <a href="#"> This link will change color<a>

Please mark an answer if you found one.

react-router-dom has an additional component called NavLink to which you can pass an additional prop called activeClassName . This will allow you to give custom styles to your active link.

example:

<NavLink to="/faq" activeClassName="selected">
  FAQs
</NavLink>

This component will replace all of your Link components in your navigation.

const [selectedItem, setSelectedItem] = useState(0);

        <nav>
          <ul className="nav-wrapper">
            <li>
              <Link className={`link ${selectedItem===0?'active':''}`}  to="/" onClick={()=>setSelectItem(0)}>
                Home
              </Link>
            </li>
            <li>
              <Link className={`link ${selectedItem===1?'active':''}`} to="/gallery" onClick={()=>setSelectItem(1)}>
                Gallery
              </Link>
            </li>
            <li>
              <Link className={`link ${selectedItem===2?'active':''}`} to="/about" onClick={()=>setSelectItem(2)}>
                About
              </Link>
            </li>
          </ul>
        </nav>

and then you can write on CSS,

 li .active{
     color: #your color;
 }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM