14

I am learning react and I started by using styled-components and react-router dom

But I face difficulties apply my custom styled component to an existing component not created by me.

Here is the code:

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

const NavStyle = styled.div`
  color: red;
  margin: 10px;
`;

const Navigation = () => {
  return (
    <div>
      <NavStyle>
        <NavLink to="/">Home</NavLink>
      </NavStyle>
      <NavLink to="/about">About</NavLink>
      <NavLink to="/contact">Contact</NavLink>
    </div>
  );
};

export default Navigation;

The problem is that color: red is not applied, but margin: 10px is applied in the view. Why so?

Hairi
  • 3,318
  • 2
  • 29
  • 68

2 Answers2

15

You can simplify styles. No need to wrap a link with another component. Simple use styled-components extending with styled() function:

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

const StyledNavLink = styled(NavLink)`
  color: red;
  margin: 10px;
`;

const Navigation = () => {
  return (
    <div>
      <StyledNavLink to="/">Home</StyledNavLink>
      <StyledNavLink to="/about">About</StyledNavLink>
      <StyledNavLink to="/contact">Contact</StyledNavLink>
    </div>
  );
};

export default Navigation;
Kort
  • 420
  • 3
  • 10
  • 1
    Do you know how you can accomplish this if the third party component has style props like the slider below? props.theme.colors.primary}`} minimumTrackTintColor={`${props.theme.colors.primary`} maximumTrackTintColor={`${props.theme.colors.primary}`} /> const StyledSlider = styled(Slider)` What can you place here? ` – yazmnh87 Jan 11 '20 at 04:34
3

You should set style for a Tag:

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

const NavStyle = styled.div`
  margin: 10px;
  a {
    color: red;
  }
`;

const Navigation = () => {
  return (
    <div>
      <NavStyle>
        <NavLink to="/">Home</NavLink>
      </NavStyle>
      <NavLink to="/about">About</NavLink>
      <NavLink to="/contact">Contact</NavLink>
    </div>
  );
};

export default Navigation;
Omid Nikrah
  • 2,444
  • 3
  • 15
  • 30