Skip to content
Advertisement

How can I style :visited elements that use React’s onClick=”” instead of href=””?

  • The website has a table.
  • In the table, I get data from the Firestore (and display this data to the user). Some cells in the table may link to other pages on the site (which are also implemented as a table).

Since there is a lot of information, the user can get confused which links they followed and which they have not touched; thus, I would like to mark with a different color when hovering over those links that the user has already visited.

By default, my link color is black, and if you hover over the link, it lights up blue. I would like the links visited by the user to be highlighted in a different color.

Below is an example of how I write the route

export default function DeviceCell({ device }) {
    const router = useNavigate()

    return (
        <TableRow>
          
            <TableCell>
                <a className="page-links" onClick={() => router(device.id)}>List of users</a>
            </TableCell>
        </TableRow>
    );
}

Also my .css file

.page-links {
    color: #3A3A3F;
    text-decoration: none;
    border-bottom: 1px black solid;
    border-bottom-width: 2px;
    cursor: pointer;   
}
    
.page-links:hover {
   color: #485FED;
   border-bottom: 1px #485FED solid;
   border-bottom-width: 2px;
}

Advertisement

Answer

If we want to use :visited CSS pseudo selector, basically we have to create browser history because visited pseudo selector depends on it. Way to do it without creating real navigation with HTML anchor element is History API. To solve this issue, we have to add symbolic href to our link for pushing history states and preventing default HTML link navigation event behaviour.

An appropriate example can be found on this code sandbox and sandbox preview

export default function DeviceCell({ device }) {
const router = useNavigate()
const handleClick = (e) => { 
   // Prevent default HTML Anchor Event
   e.preventDefault();
   window.history.pushState({ data: device.id }, `Data: ${device.id}`, e.target.href);
   router(device.id)
}
return (
    <TableRow>
      
        <TableCell>
            <a href={`/user/${device.id}`} className="page-links" onClick={handleCLick}>List of users</a>
        </TableCell>
    </TableRow>
)}

CSS:

a.page-links:hover:visited {
  background-color: #dc2626;
  color: white;
}
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement