Samuel Fajreldines

I am a specialist in the entire JavaScript and TypeScript ecosystem.

I am expert in AI and in creating AI integrated solutions.

I am expert in DevOps and Serverless Architecture

I am expert in PHP and its frameworks.

+55 (51) 99226-5039 samuelfajreldines@gmail.com

A Complete Guide to Styled-Components

Introduction

In the evolving world of front-end development, styling components efficiently and maintainably has become a crucial aspect of building applications. Styled-components is a popular library in the React ecosystem that leverages the power of CSS-in-JS to enhance the styling process. This comprehensive guide will walk you through why styled-components is a game-changer and how to effectively use it in your React projects.

Why Use Styled-Components?

Scoped Styling

Styled-components allow you to write CSS directly in your JavaScript files, ensuring that styles are scoped to specific components. This eliminates style conflicts and makes your components self-contained.

Dynamic Styling

You can easily create dynamic styles based on props and state. This flexibility enables you to adjust styles in response to user interactions without the need for complex CSS class manipulations.

Improved Maintainability

By co-locating styles with their respective components, your codebase becomes more organized and maintainable. This approach simplifies the debugging process and enhances readability.

Automatic Vendor Prefixing

Styled-components handle vendor prefixes automatically, ensuring that your styles are compatible across different browsers without extra effort.

Getting Started with Styled-Components

Installation

To begin using styled-components in your project, install it via npm or yarn:

npm install styled-components

or

yarn add styled-components

Basic Usage

Here's how to create a styled button component:

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

const Button = styled.button`
  background-color: #6200ee;
  color: white;
  padding: 10px 15px;
  border: none;
  border-radius: 5px;
  cursor: pointer;
  
  &:hover {
    background-color: #3700b3;
  }
`;

const App = () => (
  <Button>Click Me</Button>
);

export default App;

In this example, we imported styled from styled-components and used it to create a styled button element with CSS styles.

Styling with Props

Styled-components allow you to pass props to your styled elements to conditionally apply styles.

const Button = styled.button`
  background-color: ${props => props.primary ? '#6200ee' : '#white'};
  color: ${props => props.primary ? 'white' : '#6200ee'};
  padding: 10px 15px;
  border: ${props => props.primary ? 'none' : '2px solid #6200ee'};
  border-radius: 5px;
  cursor: pointer;
  
  &:hover {
    background-color: ${props => props.primary ? '#3700b3' : '#f2e7fe'};
  }
`;

const App = () => (
  <>
    <Button primary>Primary Button</Button>
    <Button>Secondary Button</Button>
  </>
);

export default App;

By passing the primary prop, we can toggle the button's styles dynamically.

Extending Styled Components

You can create new styled components by extending existing ones:

const OutlineButton = styled(Button)`
  background-color: transparent;
  color: #6200ee;
  border: 2px solid #6200ee;
  
  &:hover {
    background-color: #f2e7fe;
  }
`;

Now, OutlineButton has all the styles of Button with additional overrides.

Theming with Styled-Components

Styled-components offer a powerful theming solution using the ThemeProvider.

import { ThemeProvider } from 'styled-components';

const theme = {
  primary: '#6200ee',
  secondary: '#03dac6',
};

const Button = styled.button`
  background-color: ${props => props.theme.primary};
  color: white;
  padding: 10px 15px;
`;

const App = () => (
  <ThemeProvider theme={theme}>
    <Button>Themed Button</Button>
  </ThemeProvider>
);

This approach centralizes your color schemes and style variables.

Creating a Complete Example Application

Let's build a basic to-do application to see styled-components in action.

Setting Up the Project

First, create a new React application and install styled-components:

npx create-react-app styled-components-todo
cd styled-components-todo
npm install styled-components

Structuring the App

We'll create three components:

  • App: The main component.
  • TodoList: Displays the list of to-dos.
  • TodoForm: A form to add new to-dos.

App Component

// src/App.js
import React, { useState } from 'react';
import styled from 'styled-components';
import TodoForm from './TodoForm';
import TodoList from './TodoList';

const Container = styled.div`
  max-width: 500px;
  margin: 50px auto;
  padding: 20px;
  background-color: #f2e7fe;
  border-radius: 10px;
`;

const Title = styled.h1`
  text-align: center;
  color: #6200ee;
`;

const App = () => {
  const [todos, setTodos] = useState([]);

  const addTodo = text => {
    const newTodos = [...todos, { text }];
    setTodos(newTodos);
  };

  return (
    <Container>
      <Title>Styled Components To-Do App</Title>
      <TodoForm addTodo={addTodo} />
      <TodoList todos={todos} />
    </Container>
  );
};

export default App;

TodoForm Component

// src/TodoForm.js
import React, { useState } from 'react';
import styled from 'styled-components';

const Form = styled.form`
  display: flex;
  margin-bottom: 20px;
`;

const Input = styled.input`
  flex: 1;
  padding: 10px;
  border: 2px solid #6200ee;
  border-radius: 5px;
  margin-right: 10px;
  font-size: 16px;
`;

const Button = styled.button`
  background-color: #6200ee;
  color: white;
  padding: 0 20px;
  border: none;
  border-radius: 5px;
  font-size: 16px;
  cursor: pointer;
  
  &:hover {
    background-color: #3700b3;
  }
`;

const TodoForm = ({ addTodo }) => {
  const [value, setValue] = useState('');

  const handleSubmit = event => {
    event.preventDefault();
    if (!value) return;
    addTodo(value);
    setValue('');
  };

  return (
    <Form onSubmit={handleSubmit}>
      <Input
        type="text"
        placeholder="Add a new task"
        value={value}
        onChange={e => setValue(e.target.value)}
      />
      <Button type="submit">Add</Button>
    </Form>
  );
};

export default TodoForm;

TodoList Component

// src/TodoList.js
import React from 'react';
import styled from 'styled-components';

const List = styled.ul`
  list-style: none;
  padding-left: 0;
`;

const ListItem = styled.li`
  background-color: white;
  padding: 15px 20px;
  border-bottom: 1px solid #ddd;
  
  &:nth-child(even) {
    background-color: #fafafa;
  }
`;

const TodoList = ({ todos }) => (
  <List>
    {todos.map((todo, index) => (
      <ListItem key={index}>{todo.text}</ListItem>
    ))}
  </List>
);

export default TodoList;

Running the Application

Start the development server:

npm start

Navigate to http://localhost:3000 to interact with your styled to-do app.

Conclusion

Styled-components revolutionize the way we style React applications by combining the power of JavaScript and CSS. They provide:

  • Scoped and Dynamic Styles: Prevent style conflicts and adapt styles based on component props.
  • Improved Maintenance: Keep styles close to their components for better organization.
  • Theming Support: Easily implement themes across your application.

By integrating styled-components into your workflow, you enhance both the developer and user experience. This guide has provided you with the knowledge and practical examples to start using styled-components confidently.

Additional Tips

  • Global Styles: Use createGlobalStyle for styles that should be applied globally.
  • Refactoring: Gradually refactor existing styles when integrating styled-components into an existing project.
  • Performance: Styled-components are optimized for performance, but ensure to monitor and test your application.

Further Reading



Resume

Experience

  • SecurityScoreCard

    Nov. 2023 - Present

    New York, United States

    Senior Software Engineer

    I joined SecurityScorecard, a leading organization with over 400 employees, as a Senior Full Stack Software Engineer. My role spans across developing new systems, maintaining and refactoring legacy solutions, and ensuring they meet the company's high standards of performance, scalability, and reliability.

    I work across the entire stack, contributing to both frontend and backend development while also collaborating directly on infrastructure-related tasks, leveraging cloud computing technologies to optimize and scale our systems. This broad scope of responsibilities allows me to ensure seamless integration between user-facing applications and underlying systems architecture.

    Additionally, I collaborate closely with diverse teams across the organization, aligning technical implementation with strategic business objectives. Through my work, I aim to deliver innovative and robust solutions that enhance SecurityScorecard's offerings and support its mission to provide world-class cybersecurity insights.

    Technologies Used:

    Node.js Terraform React Typescript AWS Playwright and Cypress