Reputation: 21
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
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
Reputation: 36905
There are a couple of issues to address.
You can follow along on CodeSandbox.
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>
);
Component B
There are three issues here.
styled()
function.Instead of const CustomA = styled(<A />)
where <A />
is an instance,
Do const CustomA = styled(A)
.
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" />;
The last issue is that, you aren't passing the title
(I also did className = ""
in Component A
to make it optional).
Upvotes: 7
Reputation: 200
try
const CustomA = styled(A)`
padding-left: 20px;
`;
Upvotes: -2