After learning the basics, I set about migrating my codebase to Styled Components. In doing so, I gradually uncovered some issues and inefficiencies. There were little things here and there that I wanted to do, but couldn’t, with the knowledge I had. Many of these, I solved in roundabout ways so they weren’t major issues. But, it was enough for me to dive back into the Styled Components documentation. Luckily for me, the contributors of Styled Components had already figured them out.

Style Objects

Sometimes we are forced to use style objects via the style prop. This could be because the codebase is only partially migrated to Styled Components or because some third party library uses it, something quite common with hooks-based libraries such as React Dropzone or React Table. Styled Components can merge these style objects into Styled Component styling.

const StylePropButton = styled(Button)`
  ${props => props.$style ?? {}}
`;

const App = () => {
  return (
    <StylePropButton
      $style={{ backgroundColor: '#007bff' }}
      onClick={() => alert('clicked!')}
      type="button"
    >
      Primary
    </StylePropButton>
  );
};

Style Prop Button

Style Prop Button

This component accepts an inline style object that is then merged into the Styled Components styles by simply returning the object into the template literal. The result is a seamless integration between two drastically different ways of styling React.

Note the I’ve named the prop $style instead of style. This prevents the styles from being applied twice. If the prop name was style, the button would be styled via inline styles as well since Styled Components passes props to the underlying component. Props with names that are prefixed with $, called transient props, are only used by the defined Styled Component and are not passed down to the underlying component.

So why do it this way? You could just use the style prop directly and not merge the the style object into the Styled Components styles. The main advantage is dealing with specificity. Inline styles will always be at a higher priority than external CSS through Styled Components. This method will prevent the use of inline styles and instead convert them into external CSS via Styled Components. Then, you can easily override those styles as you see fit, without the need for !important.

#web-development #javascript #styled-components #css #react

The Advanced Way to Style with Styled Components
6.10 GEEK