Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Styling a Router Link with styled-components

What is the best way to style the Link using the styled-components library in the code that follows. I can find lots of examples to work with anchor tag but none to work with react-router link. Am I going about the correct way.

import React from "react";
import { Link } from "react-router-dom";
import styled from "styled-components";

const Nav = ({ className }) => {
  return (
    <div className={className}>
      <ul>
        <li>
          <Link to="/">Home</Link>
        </li>
        <li>
          <Link to="/about">About</Link>
        </li>
      </ul>
    </div>
  );
};
export default styled(Nav)`
  color: white;
  text-align: left;
  background: teal;
  width: 100%;
  ul {
    color: red;
    display: flex;
    flex-direction: row;
    border: 1px solid green;
    list-style: none;
    li {
      padding: 15px 15px;
      border: 2px solid purple;
    }
  }
`;

Thanks Joseph Shanahan

like image 579
Joseph Shanahan Avatar asked Dec 11 '19 15:12

Joseph Shanahan


People also ask

Can you use styled-components with SCSS?

SCSS-like Syntax: StylisStylis, a light-weight CSS pre-processor allows styled-components to use SCSS-syntax and Sass features like nesting, name-spacing and more. import React from "react" ; import styled from "styled-component" ; ## Creating a button styled-component that will render a button with some styles.

Are styled-components still good?

Styled components are a good choice for building a UI library since everything can be in one file and easily be exported and reused. If you prefer writing pure CSS, use CSS modules. You can have separate CSS files, and it locally scopes styles by default.

How can you apply dynamic styles to styled-components?

One way to dynamically change css properties with styled components is to insert a custom prop into your React component and access said property using the dollar sign and curly braces commonly used for template literals. Our current example is testing to see if our use pointer prop is true.


1 Answers

Yes thanks for your help. A slimmed down version of what I will implement is as follows. It also has the advantage in that I did not have to implement an unordered list.

import React from "react";
import { Link } from "react-router-dom";
import styled from "styled-components";

const Nav = ({ className }) => {
  return (
    <div className={className}>
      <NavLink to="/">Home</NavLink>
      <NavLink to="/about">About</NavLink>
    </div>
  );
};
const NavLink = styled(Link)`
  padding: 20px;
  color: white;
  text-decoration: none;
  &:hover {
    color: red;
    background: blue;
  }
`;
export default styled(Nav)`
  color: white;
  width: 100%;
  display: flex;
  justify-content: flex-end;
`;

Thanks Joseph Shanahan

like image 197
Joseph Shanahan Avatar answered Oct 03 '22 05:10

Joseph Shanahan