Search code examples
javascriptreactjsstyled-components

How to apply Styled Component styles to a custom React component?


I have a Styled Component called StyledButton and a React component called AddToCart. I want to apply the styled from StyledButton to AddToCart.

I have already tried the following:

import styled from "styled-components";
import AddToCart from "./AddToCart";
import StyledButton from "./styles/StyledButton";

const StyledAddToCart = styled(AddToCart)`
  ${StyledButton}
`;

What I want to do is already in the documentation at https://www.styled-components.com/docs/basics#styling-any-components but this applies new styles to the component. The problem is that I want to use existing styled from a Styled Component (StyledButton)

From the documentation:

// This could be react-router-dom's Link for example
const Link = ({ className, children }) => (
  <a className={className}>
    {children}
  </a>
);

const StyledLink = styled(Link)`
  color: palevioletred;
  font-weight: bold;
`;

render(
  <div>
    <Link>Unstyled, boring Link</Link>
    <br />
    <StyledLink>Styled, exciting Link</StyledLink>
  </div>
);

I would really like to have the styles from StyledButton applied to StyledAddToCart without copying the styles manually.


Solution

  • You can share styling with the css util:

    // import styled, {css} from 'styled-components'
    const {css} = styled;
    
    const Link = (props) => <a {...props} />
    
    const sharedBtnStyle = css`
      color: green;
      border: 1px solid #333;
      margin: 10px;
      padding: 5px;
    `;
    
    const StyledButton = styled.button`
      ${sharedBtnStyle}
    `;
    
    const AddToCartBtn = styled(Link)`
      ${sharedBtnStyle}
      color: red;
    `;
    
    function App() {
      return (
        <div>
          <StyledButton>styled button</StyledButton>
          <div />
          <AddToCartBtn>styled link</AddToCartBtn>
        </div>
      );
    }
    
    const rootElement = document.getElementById("root");
    ReactDOM.render(<App />, rootElement);
    <script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
    <script src="https://unpkg.com/styled-components/dist/styled-components.min.js"></script>
    <div id="root"/>