Styled Components Basics
How to effectively use Styled Components to create lively displays for your React Apps
What are styled components?
Glad you asked! If you are new to React and are looking for an interactive way to work on your CSS skills, as well as introduce a new styling tool, you’ve come to the right place. They are a CSS-in-JS tool, meaning that you are directly altering the JS code instead of the HTML. It’s used by many large companies, such as Google, Spotify, Github, etc.
Styled components allow your code to be more readable, as you are adding styling code directly to the component, rather than in a separate CSS file. In other words, you lose the necessity of having to sort through several class names per component.
When you are creating a styled component, you are essentially creating a regular React component, with the addition of adding styles directly to it.
How to Install
yarn add styled-components
OR
npm i styled-components
My Experience
Styled components made my life so much easier when working on my final project at the Flatiron School. There are many ways to style UI for your projects, and at times they may seem overwhelming. Libraries like Bootstrap or Material UI do most of the heavy lifting for you, and can be a tremendous help if you aren’t very CSS savvy.
However, learning styled-components can be a nice and helpful way to learn React component styling, as well as HTML and CSS. Like I stated previously, it is a CSS-in-JS tool, so a majority of the main CSS rules still stand.
How to Use
In styled-components, you style directly into the component. Where you would normally use classNames, divs, h1s, etc, basically any HTML element, you will actually use the styled element to help indicate what you want styled a specific way. But before we do this, we want to import the styled-components into your React component. At the top of your file, put:
import styled from 'styled-components'
Below your code, this is where you can begin loading your CSS! For example, let’s say that we want to style a button within a div. You can create separate CSS components for each HTML element, and include it within the same React component file. In order to create the styled-component, set a variable equal to styled.whatever-html-element-you-are-trying-to-style, and use two back ticks to encompass the styling. Let’s see a quick example.
These are the very basic rules of setting up styled-components. The same CSS rules apply for styled-components, and you can create global components, as well, in order to encompass multiple React components as once.