Styled-components: Override component style inside a new component

I am trying to override the style of a component inside another component.

So, I have a component A, with some div's inside(Wrapper, Header). In a new component, I am trying to override component A. Inside that override I want some new styling to the Header component. I know I can reference a component inside the same component but I can't find any info about referencing inside a new component.

// Component A
import React from "react";

export default ({
  className,
  title
}) => (
    <Wrapper className={className}>
      <Header>{title}</Header>
    </Wrapper>
  )
);

const Header = styled.h2`
  padding-left: 0;
`;

// Component B
import React from "react";

export default () => (
    <CustomA>
      /* content */
    </CustomA>
  )
);

const CustomA = styled(<A />)`
  ${Header} {
    padding-left: 20px;
  }
`;

I expect Header to be changed but I get "Header is not defined".

Upvotes: 2

Views: 19462

Answers (3)

Ahmed Waqas
Ahmed Waqas

Reputation: 255

First of all you need to use styled like below:

const CustomA = styled(A)``;

instead of

const CustomA = styled(<A/>)``;

Secondly, try the following code:

const CustomA = styled(A)`
  h2{
    padding-left: 20px;
  }
`;

Upvotes: -1

dance2die
dance2die

Reputation: 36905

There are a couple of issues to address.

You can follow along on CodeSandbox. Edit so.answer.57203735

1. Export Header component from Component A

You need to make Header component available outside Component A so that it can be referenced within Component B.

import React from "react";
import styled from "styled-components";

export const Header = styled.h2`
  padding-left: 0;
`;

export default ({ className = "", title }) => (
  <div className={className}>
    <Header>{title}</Header>
  </div>
);

2. Errors in Component B

There are three issues here.

  1. You need to pass the component name, not the instance to styled() function.

Instead of const CustomA = styled(<A />) where <A /> is an instance,
Do const CustomA = styled(A).

  1. You need to import Header component exported from Component A.
    Now you can reference is within styled(A) as ${Header}.

    import styled from "styled-components";
    
    import A, { Header } from "./CustomA";
    
    const CustomA = styled(A)`
      ${Header} {
        padding-left: 20px;
      }
    `;
    
    export default () => <CustomA title="Component B Content" />;
    
  2. The last issue is that, you aren't passing the title (I also did className = "" in Component A to make it optional).

Upvotes: 7

try

const CustomA = styled(A)`
    padding-left: 20px;
`;

Upvotes: -2

Related Questions