Intro To Styled Components

The idea of CSS in JS was a concept that was first talked about in 2014 and some dismissed it as nonsense. However, there are some really well supported and active libraries that can you use in your project that take advantage of CSS in JS. One of those is styled-components. If you remember our JavaScript template literals post you might remember we mentioned styled-components there. Using styled-components allow you to keep your styles very tightly coupled with your individual components, and can make components more readable. Another plus is that components can be very testable for stylistic properties. Using something like jest styled components you can directly test for styling properties that your components should have.

A styled component looks like this:

import styled from 'styled-components';

const Title = styled.h1`
  font-size: 1.5em;
  text-align: center;
  color: red;
`;

Overall, there are pros and cons to using styled components, and like most things in web development the answer if you should use it or not, is “it depends…”. Play around with it, and see if it fits your use case! Read more about styled components.

Instagram Post