technology/como-usar-styled-components.mdx
Technology

Improve your app's styles with Styled Components

Styling in React has always been problematic. It's very common to import the wrong styles, get class names wrong or overwrite other styles. What if I told you you can fix these with just JavaScript?

10 min readMarch 8, 2020

Styling in React has always been problematic. It's very common to import the wrong styles, get class names wrong or overwrite other styles. What if I told you you can fix these issues using only JavaScript?

Styled Components is a library that helps us solve these problems through CSS in JS, letting us write CSS code directly in JavaScript.

To install this dependency, just run this command in your project terminal:

npm install --save styled-components

Once it's done installing, you just declare your components as you always have, but this time we'll import Styled Components to add some style. The following example shows you clearly how it's done:

import React from "react";
import styled from "styled-components";

// We style a div tag that will be called "Container"

const Container = styled.div`
display: flex;
justify-content: center;
height: 100vh;
background: linear-gradient(to right, #ec008c, #fc6767);
`;

// We style an h1 tag that will be called "Title"

const Title = styled.h1`
font-family: Arial, Helvetica, sans-serif;
font-size: 56px;
color: white;
line-height: 1.5;
margin-top: 200px;
max-width: 500px;
`;

const Home = () => {
	return (
		<Container>
			<Title>Hello world with Styled Components 💅</Title>
		</Container>
	);
};

export default Home;

This component is a home page with a title that looks like this in the browser:

Hello world with Styled Components

As you can see, styling a full page and its components is very simple with this library. We can use any HTML tag we want, add styles directly to it and turn it into a React component.

The main improvements Styled Components has over traditional CSS are:

  • Encapsulates your CSS: Only the CSS you declare in your component will affect it and it won't mix with any other styles.

  • Loads only the CSS you need: Styled Components only loads the styles of components that are shown on screen, so you don't have to load all your app's styles from the start.

  • No more class name mistakes: Each created class name gets a unique hash. This hash prevents two classes from having the same name and keeps their styles from mixing.

This dependency makes developing and styling our app much easier. It's not only for declaring our styles—Styled Components has some aces up its sleeve with very useful features to speed up our development. For example, a couple of them are:

Properties straight into your CSS

This is one of the coolest features. Since it's just JavaScript you can pass properties to your component to change its CSS. This makes styling fully dynamic, just like your components.

import React from "react";
import styled from "styled-components";

/* If the button receives the "isRed" prop it will turn
   red, otherwise it will be blue. */

const Button = styled.button`
	background: ${props => (props.isRed ? "red" : "blue")};
	color: white;
	border: none;
	padding: 5px;
	border-radius: 5px;
`;

const Buttons = () => {
	return (
		<>
			<Button isRed>I'm red</Button>
			<Button>I'm blue</Button>
		</>
	);
};

export default Buttons;

Create themes with ThemeProvider

Styled Components includes a component for adding themes called ThemeProvider. With it we can supply different colors or sizes to our components, achieving a much more consistent design in an easy and quick way.

// Import the Theme Provider
import styled, { ThemeProvider } from "styled-components";
// Create our theme with the colors we want.
const theme = {

	// Light theme colors
	light: {
		background: "#fdd835",
		color: "#212121"
	},
	// Dark theme colors
	dark: {
		background: "#212121",
		color: "#fdd835"
	}
};

/* If dark mode is on, dark theme colors are used,
   otherwise the light theme is used */

const Wrapper = styled.div`
	background: ${props =>
		props.darkMode
		? props.theme.dark.background
		: props.theme.light.background};

	h1 {
		color: ${props =>
			props.darkMode 
			? props.theme.dark.color 
			: props.theme.light.color};
		}
`;

const ThemedPage = () => {
	return (
		<div>
		{/* Add the theme with ThemeProvider */}
			<ThemeProvider theme={theme}>
				<Wrapper>
					<h1>Light theme</h1>
				</Wrapper>
				<Wrapper darkMode>
					<h1>Dark theme</h1>
				</Wrapper>
			</ThemeProvider>
		</div>
	);
};

Light and dark theme

Creating a dark theme in React had never been so easy!

In general Styled Components is full of surprises. You can change the styles of components from other frameworks like Gatsby or Next; create your own animations and reuse them in different parts of your project; inject styles in your Server Side Rendering with just a few lines of code or create global CSS configurations.

For these amazing reasons many companies like Airbnb, Patreon, Target and Ticketmaster are already using it on their sites. Don't wait any longer and discover everything this dependency has to offer.

Don't leave with doubts and learn to master this library in the Advanced React Course where you'll find a whole module focused on using Styled Components.

Never stop learning!