My Journey

Like many, I first started styling React with inline CSS. It was an adjustment coming from stylesheets but I really liked the ability to define localized styles and leverage the power of Javascript. Of course, there were issues such as performance and lack of pseudo-selector support, but overall I was happy with it and there was no compelling reason or deficiency to search for another way to style my components.

When I was first introduced to Styled Components, I was a bit apprehensive of the benefits, having gotten used to inline CSS for so long. After all, React documentation (at the time), still used inline CSS for all their examples. As I prototyped the framework, I discovered a best of both worlds between inline CSS and traditional stylesheets.

Styled Components

While defined very differently, Styled Components act fundamentally like React components. They both take props as input and output HTML.

Let’s take this sample button component styled similarly to Bootstrap’s buttons with Styled Components.

import styled from 'styled-components';

const Button = styled.button`
  display: inline-block;
  padding: 6px 12px;
  font-size: 16px;
  font-family: Arial, sans-serif;
  line-height: 1.5;
  color: white;
  background-color: #6c757d;
  border: none;
  border-radius: 4px;
  :not(:disabled) {
    cursor: pointer;
  }
  :hover {
    background-color: #5a6268;
  }
`;

The styled component factory is imported and used to generate a button with styles using a template literal (...). This factory supports all valid HTML elements whether that be divh1p, etc. Similarly, the styles in the template literal accepts all valid CSS so you can go crazy with complex CSS selectors.

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

The Modern Way to Style React Apps with Styled Components
2.35 GEEK