Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Apply styled component style to a third party components

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?

like image 426
Hairi Avatar asked Sep 09 '18 11:09

Hairi


People also ask

Is it important to define styled-components outside of the render method?

It is important to define your styled components outside of the render method, otherwise it will be recreated on every single render pass. Defining a styled component within the render method will thwart caching and drastically slow down rendering speed, and should be avoided.

How do styled-components work under the hood?

To sum up what styled-components does under the hood, it creates CSS on the flight by creating hashes for the classes of the component being styled, secondly it puts together these classes with the styles defined by the user, then injects those to a style tag in the head of our HTML document and finally add the class ...


1 Answers

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;
like image 93
Kort Avatar answered Oct 24 '22 04:10

Kort