Styled Components 💅🏾

Ready to add another tool to your developer toolbelt? Styled-components are great for reusability, maintenance and debugging. Styled-components allow us to write CSS in JavaScript template literals.

Let’s get started!

We need to install styled-components so let’s type the command below:

npm install styled-components

Once the installation is done, let’s style our first component! We also need to import styled from ‘styled-components’ at the top of our file. For this example, I will be showing you how to style a simple button element.

You can see that we are declaring a variable called Button and it equals styled.button which is the element we are styling, right? Think of all those times you had the same button on your app and you had to go in add the className to each button element. Well, basically we are telling styled-components to take our Button variable and apply it wherever we call it. If we have this button in multiple locations we can export this styling and use it exactly like a component.

Here is what our button looks like right now without the styling:

Next, let’s add some styling.

The CSS is placed in the template literals just like before, nothing new there. Now let’s find the button element and use our styled-component.

As you can see we are rendering our styled-component using the variable we created above. Here is what the styled-component button now looks like:

Let’s say you really like the idea of styled-components but don't want to keep all the styling at the top of your component file. We can create a file called styles.js and export them into whatever component we want to use them. Let me show you the setup for using a separate file to keep all your styles in.

We are still importing styled from “styled-components”in styles.js but instead of just using const Button we are going to use export const Button. The word export allows us to access the newly styled Button component in whichever files we choose. Magical, right?

Let’s access that styled Button component from our styles.js file. Here is what the setup looks like:

We use the import keyword with { } and name of our styled-component. If you had more than one styled-component you wanted to import it would look like this:

This is the simplest most basic explanation of styled-components. There more complex features that I will explore in my next blog. Stay tuned for using props and extending styles.

Wrapping Up

Try implementing this new knowledge in one of your components and explore how styled-components will clean up your code, make debugging more straightforward, and be reusable among many components.

Official Documentation: https://styled-components.com/

Developer in NYC 🤠

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store