Styled components is a CSS-in-JS tool that helps in the gap between components and styling, giving them many features to get you up and running in styling components in a reusable and functional way. In this article, I have highlighted the basics of styled components and how they can properly be applied in our React applications. One has to have an understanding of React before going through this article.
At the core of CSS is the ability to target any HTML element globally regardless of its place in the DOM tree. This can be an obstacle when used with components, because components need, to some reasonable extent, colocation for example keeping assets such as states and styling closer to where they’re used known as localization.
Styled components are visual primitives for components, and their goal is to give us a flexible way to style components. The result is a tight coupling between components and their styles. Styled components are used for both React and React Native.
We use styled-components because it helps in scope styling and automating vendor prefixes for example one can use standard CSS properties, and styled components to add vendor prefixes here needed. The use of unique class names makes the styled components independent of each other and does not have to worry about their names because the library handles them. The elimination of dead styles is done by styled components even if they are declared in the code.
Installing a Styled Component
Installing Styled Component is easy and one can use a package manager such as yarn or npm for example,
Adapting Styled Components Based on Props
Styled components are functional, so we can easily style elements dynamically. Let’s assume we have two types of buttons on our page, one with a black background, and the other with blue. We do not have to create two styled-components for them; we can adapt their styling based on their props. For example;
Because StyledButton is a React component that accepts props, we can assign a different background color based on the existence or value of the bg prop.
If one is working on a landing page and wants to set the container to a certain max-width to keep things centered they should have a StyledContainer for that:
If one discovers that they want a smaller container, with padding of 10px on both sides, instead of 20px, they should create another styled component which will be repetition. Therefore, one should learn to reuse their styles.
Styled components can also be called global styling just like CSS in JS. Global styling helps in using similar styles once without repetition.
Styles created with createGlobalStyle do not accept any children.
Now that we have an understanding of how styledcomponents work and what should be applied in our projects, we don’t have to struggle with repeating styles in CSS. Styled Components will help reduce cumbersome work while working on our projects.