Search code examples
javascriptreactjsjsxstyled-components

Passing Children Styling Down to a Styled Component


I am making a generalized version of a styled component to replace duplicated code in my codebase. The component looks something like this:

const CustomDiv = styled.div`
  display:flex;
  b {
     padding-right:5px
   }
`;

const DivWrapper = ({style, children}) => {
  return (
    <CustomDiv style={style}>
      {children}
    </CustomDiv>
  );
};

I want to be use this "DivWrapper" in other places of the code base but be able to change the b padding in other places when using it. I tried extending it like this:

const SuperCustomDiv = styled(CustomDiv)`
  b {
    padding-right:10px
  }
`;

I am using the styled components library for React.


Solution

  • You can achieve this by using css props and passing props from the styled-component to the CSS. So, we create styled CSS with some property, then this style place to both styled components. With props, we will pass the value to main style.

    import styled, { css } from "styled-components";
    
    const PaddingStyle = (value) => css`
      padding-right: ${value}px;
    `;
    
    export const SuperCustomDiv = styled.b`
      ${PaddingStyle((props) => props.padding)}
    `;
    
    export const CustomDiv = styled.div`
      display: flex;
      b {
        ${PaddingStyle((props) => props.padding)}
      }
    `;
    
    export const DivWrapper = ({ padding = 50, children }) => {
      return (
        <CustomDiv as="div" padding={padding}>
          <b>Name:</b> {children}
        </CustomDiv>
      );
    };
    
    export default function App() {
      return (
        <div className="App">
          <DivWrapper>John Doe</DivWrapper>
          <SuperCustomDiv padding={30}>Super</SuperCustomDiv>
          <span>John Smith</span>
        </div>
      );
    }
    

    Edit dazziling-code