Search code examples
javascriptcssreactjsstyled-components

Unable to override Styled Component in React


I have a BaseComponent in one file, which is made up of several other components and I am exporting that component. The highest level of the BaseComponent has a wrapper that is responsible for the margin. When I export it and try to overwrite some of the styles with

 //other file

const BaseComponentWrapper = styled.div`
  margin: 10px
`

const export BaseComponent = () => {
  return (
      <BaseComponentWrapper>
          Some other stuff in the middle
      </ BaseComponentWrapper >
}
import { BaseComponent } from otherfile

const ModifiedBaseComponent = styled(BaseComponent)`
  margin: 0 px;
`

The margin does not change to 0px for my ModifiedBaseComponent.

The only way I have been able to change the margin is to take the class produced by styled components from the browser and plug it in under the wrapper css for example

const BaseComponentWrapper {
  .etbykw {
     margin: 0px;
  }
}

From what I am aware of at the very least this code below should work but it also does not

const BaseComponentWrapper {
  > ${ModifiedBaseComponent} {
     margin: 0px;
  }
}

From what I have seen on other questions there is something about a className prop that might be useful but I am unable to understand this. I know it's a specificity problem of some kind but I am really struggling to fully understand this and the code that works is not very readable from an outside party.


Solution

  • To style a commonly component, you must pass the className property.

    In the example below, the BaseComponent takes a className and passes it to the BaseComponentWrapper.

    Now you can style your BaseComponent.

    Docs: https://styled-components.com/docs/advanced#styling-normal-react-components

    const BaseComponentWrapper = styled.div`
      margin: 10px;
    `;
    
    export const BaseComponent = ({ className, children }) => {
      return (
        <BaseComponentWrapper className={className}>
          {children}
        </BaseComponentWrapper>
      );
    };