Search code examples
cssreactjsstyled-components

How to remove styling from Link of react router with styled-components


I'm using styled-components but in a different file. I've searched for this question and found many answers, but I'm still confused about how to apply it in my code version. So, sorry in advance if it will be repetitive.

File Main.jsx :

import { BrowserRouter as Router, Switch, Route, Link } from "react-router-dom";

function Main() {
  return (
    <>
      <Router>
        <MainComponent>
          <Menu>
            <Link to="/crypto">
              <HyperLink>Crypto</HyperLink>
            </Link>
            <Link to="/marketplace">
              <HyperLink>Market Place</HyperLink>
            </Link>
          </Menu>
          <Switch>
            <Route path="/crypto" component={Crypto} />
            <Route path="/marketplace" component={MarketPlace} />
          </Switch>
        </MainComponent>
      </Router>
    </>
  );
}

File MainElements.jsx:

import styled from "styled-components";

export const MainComponent = styled.div`
  width: 100%;
  height: 100vh;
  background-color: #1e2258;
`;

export const Menu = styled.div`
  display: flex;
  width: 80%;
  margin: auto;
  height: 10vh;
  color: #fff;
  border: 1px solid white;
  align-items: center;
`;

export const HyperLink = styled.p`
  text-decoration: none;

  &:focus,
  &:hover,
  &:visited,
  &:link,
  &:active {
    text-decoration: none;
  }
`;

Solution

  • Can try example from react-router docs https://reactrouter.com/web/api/Link/component-reactcomponent

    Just use a tag instead of p for link.

    const FancyLink = React.forwardRef((props, ref) => (
      <HyperLink ref={ref} {...props}>{props.children}</HyperLink>
    ))
    
    <Link to="/" component={FancyLink} />
    
    const CustomLink = ({ ...props }) => <Link component={FancyLink} {...props} />