Reputation: 72
SharedButton
is the base style of a button inside my app, and it is shared across components. I am trying to override the styles of this button inside MyComponent
.
I am getting the following error when myComponent
mounts:
ReferenceError: Cannot access 'SharedButton' before initialization
.
Note that If I don't import SharedButton
from a different file, ie. if I define it inside "MyComponent", I don't get the error. How can I solve this issue?
shared.ts
import styled from "styled-components";
export const SharedButton = styled.button`
border: 1px solid red;
color: #1c101e;
font-size: 14px;
`;
myComponent.ts
import { SharedButton } from "./shared";
import styled from "styled-components";
const MyComponentButton = styled(SharedButton)`
float: right;
`;
const MyComponent = () => {
return <MyComponentButton> TEST </MyComponentButton>
}
Upvotes: 3
Views: 2767
Reputation: 8508
Try placing the MyComponentButton
style in shared.ts and export to the myComponent.ts. sandbox examples
shared.ts
import styled from "styled-components";
export const SharedButton = styled.button`
border: 1px solid red;
color: #1c101e;
font-size: 14px;
`;
export const MyComponentButton = styled(SharedButton)`
float: right;
`;
myComponent.ts
import { MyComponentButton } from "./shared";
const MyComponent = () => {
return <MyComponentButton> TEST </MyComponentButton>
}
The second approach, put some props in styled-components
shared.ts
import styled, { css } from "styled-components";
export const SharedButton = styled.button`
border: 1px solid red;
color: #1c101e;
font-size: 14px;
${({ floatRight }) =>
floatRight &&
css`
float: left;
`}
`;
myComponent.ts
import { SharedButton } from "./shared";
export const MyComponent = () => {
return <SharedButton floatRight> TEST </SharedButton>;
};
Upvotes: 1