Search code examples
javascriptreactjsnext.jscomponentsstyled-components

Override style of children elements of one component again using StyledComponents when using them in another component


I have a Component like

const CalendarComponent: React.FC = () => (
  <DropdownContainer>
    <CustomDropdown>
      <span>{label}</span>
      <ArrowIconContainer>
        <NextImage src={DownArrowIcon} />
      </ArrowIconContainer>
    </CustomDropdown>
    {isOpen && <CalendarComponent />}
  </DropdownContainer>
);

These all elements (DropdownContainer,CustomDropdown,ArrowIconContainer,CalendarComponent) are defined using StyledComponents in another file.

Now, I am using this component CalendarComponent in another component, from that component I want to override the styles of these inner elements (DropdownContainer,CustomDropdown,ArrowIconContainer,CalendarComponent) using StyledComponents.

Is this possible ? And What is the best practice to achieve this kind of scenario. It will be better if someone can explain with example as I am new to this.

I tried something as below:

const CalendarDateDropDown = styled(DropdownCalendarComponent)`
  & > div {
    display: flex;
    width: 199px !important;
    padding: 4px 16px;
    justify-content: space-between;
    align-items: center;
    align-self: stretch;
    border-radius: 8px;
    background: var(--Input-Field-Backround, #f5f5f7);
  }
`;

but its not working, I want the best practice that is followed in react community to achieve this.


Solution

  • The correct way as explained by @evolutionxbox in comments is to pass className as parameter to the container inside the child component. Then pass your custom class from parent component. Example:

    //child component
    
    const CalendarComponent: React.FC<CalendarComponentProps> = ({
      className}) => (
      <DropdownContainer className={className}>
        <CustomDropdown>
          <span>{label}</span>
          <ArrowIconContainer>
            <NextImage src={DownArrowIcon} />
          </ArrowIconContainer>
        </CustomDropdown>
        {isOpen && <CalendarComponent />}
      </DropdownContainer>
    );
    
    //Below section will be in parent component or in a separate styled file. Its not part of child component.
    
    export const CalendarDate = styled(CalendarComponent)`
      display: flex;
      width: 50px;
      height: 50px;
      padding: 50px 50px;
      justify-content: space-between;
      align-items: center;
      align-self: stretch;
      border-radius: 8px;
      span {
        color: var(--Slate-Gray, var(--Grey-text, #89909f));
        font-size: 16px;
        font-style: normal;
      }`;
    

    In this way, the custom style will be applied to DropdownContainer of calendarComponent and also on span under DropDownContainer.

    Then you can used the CalendarDate in your parent component.