简体   繁体   中英

How to use styled-components that extends from an already styled component?

I'm trying to extract all my component styling using styled-component to a single file.

However, I am running into an error where if I extract the styling and the component which the styling is reliant into a separate file, the themes stop working.

Button.jsx

import {ButtonWrapper} from './Button.styled';
import {Button as MUButton} from '@material-ui/core/Button';

export const Button = () => {
  return <ButtonWrapper>
    <Button/>
  </ButtonWrapper>
}

SmallButton.jsx

import {StyledSmallButton} from './Button.styled';

// import {Button} from './Button'

// const StyledSmallButton = styled(Button)` // This works.
//   width: 50%
// `

export const SmallButton = () => {
  return <StyledSmallButton/>
}

Button.styled.jsx

import {Button} from './Button';

export const ButtonWrapper = styled.div`
  width: 100%
`;

export const StyledSmallButton = styled(Button)` //Doesn't work.
  width: 50%
`;

Error

Uncaught Error: Cannot create styled-component for component: undefined

I believe there is a cyclic dependency problem here ie SmallButton requires Button which is themed by ButtonWrapper . How can I solve this?

I think you've imported the MUButton wrong. Should the <Button /> component actually be <MUButton /> ?

import {ButtonWrapper} from './Button.styled';
import {Button as MUButton} from '@material-ui/core/Button';
                 // ^ this is the alias

export const Button = ({ className }) => {
  return <ButtonWrapper>
    <MUButton className={className} />
     // ^ This should be MUButton
  </ButtonWrapper>
}

Edit: passed the className prop down as mentioned by Andy int he comments

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM