DEV Community 👩‍💻👨‍💻

DwightColbyJack
DwightColbyJack

Posted on

Styled Components and ReactJS

I went to school for graphic design, and while I excelled at rendering and photo manipulation, web design was always a pain-point for me. A lot of CSS, or "cascading style sheets" deal with determining the elements on your page that you would like to organize or style using class and id tags. When you know what combinations you want to group and apply styles to, the file they come from is off in another directory like "assets" or "styles" and this all follows a protocol that is somewhat standardized and accepted as best practices. However, React offers the ability to style components in line, meaning you can differentiate some components based on their change in state, their importance, or even just to shake things up for the user for a little fun.
The question is, how do we maintain a readable and understandable code base in terms of our styles. If you've got inline styles and styles from a stylesheet conflicting, it can be a pain to debug the look of your application. Styled Components makes use of tagged template literals which is a recent addition to JavaScript. Essentially scoping CSS is the name of the game with Styled Components, giving us the ability to package the many styles we want for our React Components in in components dedicated to styles alone, and using them as a "wrapper." The wrapped component will have access to styles in the wrapper and those styles can wrap ANY component we choose. The really wild thing about styled components is the syntax. Tagged template literals use the back ticks we might use to interpolate. You can then define a const variable (whatever you want to name the style-component you're making) and set it equal to "styled", like so:

const CartItemStyles = styled.li`
  padding: 1rem 0;
  border-bottom: solid var(--lightGrey);
  display: grid;
  grid-template-columns: auto 1fr auto;
  img {
    margin-right: 1rem;
  }
  h3, p {
    margin-right: 0;
  }
`;
Enter fullscreen mode Exit fullscreen mode

The li tag will define the elements to be styled with this style-component, but whatever we wrap in will adhere to these CSS rules and it can be used all over our application. React is already making my development work alot more streamlined, but finally making all that code look good is even more convenient thanks to Styled Components.

Top comments (0)

Head to your account's Settings to...

🌚 Enable dark mode
🔠 Change your default font
📚 Adjust your experience level to see more relevant content