Introduction to React Styled Components

Roberto Moreno Celta
2 min readJul 25, 2022

--

Styled-Components
https://styled-components.com/

In React.js world there are many options when it comes down to “how do I style my React application?”, in this post we will discuss the option “Styled Components”.

Styled Components?

“As you can see, styled-components lets you write actual CSS in your JavaScript. This means you can use all the features of CSS you use and love, including (but by far not limited to) media queries, all pseudo-selectors, nesting, etc.”

Basically this is a way of writing CSS inside Javascript, but what makes it different is the way we can implement the styling for each components, this is an example of how it works:

The first thing you need to do is install styled-components, you can do it with NPM or Yarn

# with npmnpm install --save styled-components# with yarnyarn add styled-components

Now you can use styled-components inside your React application, in this example we are going to create a simple ButtonComponent. If you ever used Material UI, you will find yourself coding similar stuff, but in case you are new to this, you will need to import this:

import styled from 'styled-components'

then, using this syntax you will create the Button

const Button = styled.button`padding: 10px 30px;background: honeydew;`;

And that’s it! The way you will call this component inside your applications is similar to this

function App() { return (  <>   <Button>Click me</Button>  </> );}

As you can see, things are pretty much normal CSS when creating a Components, but what I want to discuss now it the following topic: Why? Why do we need to do this and what is the benefit of using this type of tools for styling?

One thing you can do using styled-components it’s adapting based of props, in the getting started page it says:

“You can pass a function (“interpolations”) to a styled component’s template literal to adapt it based on its props.

This button component has a primary state that changes its color. When setting the primary prop to true, we are swapping out its background and text color.”

You can also extend styles, use theming (something you can see here), and many more things!

Here is a simple Repl.it already set with styled-components for you to play!

https://replit.com/@RobertoMoreno2/Introduction-to-React-Styled-Components#src/App.jsx

--

--

Roberto Moreno Celta

UX Designer & Front End Dev. Love for food, movies and video games.