Type to generate custom UI components with AI

Type to generate UI components from text

OR

Browse thousands of MUI, Tailwind, React components that are fully customizable and responsive.

Explore Components

Ultimate Guide to Using React Styled Components Like a Pro

While the component-based architectural design of building web applications with React ushered developers into an era of code re-usability, consistency, code scalability, better code organization, and even more, it is, however, with no imperfections.

The component-based architecture in React applications introduced many complexities such as rapid change, lack of standards, need for additional libraries, inadequate documentation, and a steep learning curve of JSX syntax, its usability and scalability with CSS are part of the drawbacks of this architectural pattern with the notable disadvantage being usability and scalability with CSS.

This notable drawback led to the development of solutions to address this problem – one which is styled components, otherwise known as CSS-in-JS.

What is Styled-Components

Styled-components is a CSS-in-JS styling framework that allows developers to write CSS using tagged template literals and attach it to JavaScript components.

In React applications, the styled-components library simplifies the process of building React components. This library allows you to apply styling to your components by incorporating plain CSS directly within your JavaScript code.

Styled components solve issues around CSS specificity by scoping styles within each component. Since the CSS is contained at the component level, there is no risk of class name collisions that could create unintended cascading effects across disparate parts of the UI.

Developers don’t need to worry about managing overly specific selectors or unintentionally breaking styles in unrelated components when making CSS changes. This component-level isolation of CSS allows for cleaner and more modular front-end code.

Rather than dealing with a tangled nest of global styles, developers can treat each component as a self-contained unit with encapsulated styles that don’t depend on or influence other components in the system.

The net result is greater maintainability and fewer regressions when evolving complex UIs over time.

Prerequisites

  • Knowledge of CSS, because everything about the styled-component library is merely you writing basic CSS in a React component.

  • Knowledge of React, understanding how React components work and React-JSX syntax are required for you to create styled components in a React application.

  • NPM is installed on your machine.

Before we delve ahead, check out how Purecode.ai allows you to be a 10x developer by increasing efficiency, productivity, and effectiveness.

You no longer have to go through the hurdles of writing each piece of code for your components yourself; just choose from our repository of 10, 000+ AI-generated custom components for your web application.

Creating a Button with Styled Component: Basic Example

This code example below demonstrates the basic syntax for creating a button component with the styled-component framework. It shows you can use the styled API to create custom components, with the same capabilities as the core components:

import "./styles.css";
import styled from "styled-components";

export default function App() {
  return (
    <div className="App">
      <Button>Contact Us</Button>

      <Button>About Us</Button>
    </div>
  );
}

const Button = styled.button`
  display: inline-block;
  border-radius: 3px;
  padding: 0.5rem 0;
  margin: 0.5rem 1rem;
  width: 11rem;
  background: transparent;
  color: #ff4385;
  border: 2px solid #ff4385;
  cursor: pointer;
`;

Benefits of Using Styled-Components

Using the styled-component framework offers numerous benefits which are:

  • Component-scoped styles The Styled Components framework encapsulates all CSS within the component definition itself. This eliminates issues with global style clashes or unintended cascading effects.

  • Powerful inline styling The syntax feels like writing normal CSS styles but with full access to JavaScript logic/expressions. There are no browser compatibility concerns like regular inline styles. CSS Media queries also work nicely and are supported.

  • Cross-platform mobile support For codebases using both React and React Native, the styled-components framework provides seamless integration for building consistent UIs across platforms.

  • No global specificity problems Scoped styling avoids headaches from global CSS side effects by isolating each component’s style. Changes to one component cannot affect unrelated ones. Styled Component do not conflict but remain easily identifiable in the React Developer Tools and Web Inspector.
  • Unique class names The Styled components classes are unique across your application. This is because the framework converts the class names to unique strings like .sc-HawYs instead of .button. This means that you never have to worry about duplication, overlap, or misspellings.

Other Benefits

  • Props-based styling API Styled components enforce the use of props rather than classes to explicitly control components. This leads to improved debugging, readability, and React best practices.

  • First-class theming support The theming system allows defining styles in one place and automatically passing them to all connected UI components consistently.

  • Automatic vendor prefixing The Styled-component framework automatically prefixes your CSS properties with their respective vendor prefix. Example: of how the styled-component framework will automatically prefix properties ⬇

    Regular CSS styles

    .button {
      cursor: pointer;
      border-radius: 3px;
      letter-spacing: 0;
      transition: all .5s cubic-bezier(.77,0,.175,1);
      user-select: none;
      transform: translate3d(0,100px,0);
    }
    
    

    Styled-component vendor prefixed:

    .button {
      cursor: pointer;
      -webkit-border-radius: 3px;
      -moz-border-radius: 3px;
      border-radius: 3px;
      letter-spacing: 0;
      -o-transition: all .5s cubic-bezier(.77,0,.175,1);
      -webkit-transition: all .5s cubic-bezier(.77,0,.175,1);
      transition: all .5s cubic-bezier(.77,0,.175,1);
      -webkit-user-select: none;
      user-select: none;
      -webkit-transform: translate3d(0,100px,0);
      transform: translate3d(0,100px,0);
    }
    
    

    In the code snippets above, notice the difference between the regular CSS styles and the one generated by the styled-component framework. The advantage is that you do not have to worry about your styles breaking on some browsers while being supported by others.

  • and many more benefits.

If you want to skip ahead and learn via video tutorial, check out this video below:

Setting Up a New React App

The create-react-app command-line interface (CLI) tool makes initializing a React project quick and hassle-free.

Creating the App Scaffolding

  • Run npx create-react-app my-app to scaffold a new React project using CRA

  • Handles configuring Webpack, Babel, testing, and other essential build tools

  • Ready to start coding right away? Let’s dive in 🚀

Folder Structure Best Practices

  • The source code lives in the /src folder

    • Components, utils, and styles get their folders

  • /public holds static files

  • /node_modules has third-party dependencies

  • The structure stays manageable even for large codebases

Installation

Installing styled components is easy. You can do it through a CDN or with a package manager.

Using Yarn:

yarn add styled-components

Using NPM:

npm install styled-components

Importing the styled-components Library

  • Popular for CSS-in-JS styles co-located with components

  • Import statement: import styled from ‘styled-components’

  • Define component styles directly in .js files

Once your app is set up, run the application by entering either of these commands in your terminal:

yarn start

Or using npm:

npm start

Your server should launch in your browser at http://localhost:3000/, as shown below:

Styling Your First Component

In this section, I will walk you through how to get started with styled-components. We will create a <Button /> component that will be re-usable across your entire application and can be customized depending on the props passed to the component.

Defining Reusable Styled Components

Let’s create a new component called <Button /> that has normal and primary variants:

import "./styles.css";
import styled from "styled-components";
export default function App() {
  return (
    <div className="App">
      {/* Normal */}
      <Button>Normal</Button>
      {/* Primary */}
      <Button $primary>Primary</Button>
    </div>
  );
}
const Button = styled.button``;

In the code snippet above ⬆, we are just rendering two buttons; the only difference is that the second button has a property named $primary.

When the buttons are rendered, they will look similar to the screenshot below:

Next, let’s style our buttons a bit. First import styled and define the base button:

import styled from 'styled-components';
const Button = styled.button``;

The backticks tag are tagged template literals used to style; see MDN 📝docs on tagged template literal.

import "./styles.css";
import styled from "styled-components";
export default function App() {
  return (
    <div className="App">
      <Button>Normal</Button>
      {/* Primary */}
      <Button $primary>Primary</Button>
    </div>
  );
}
const Button = styled.button`
  display: inline-block;
  background: transparent;
  border: 1px solid #ff4385;
  border-radius: 4px;
  color: #ff4385;
  font-weight: 600;
  cursor: pointer;
  text-decoration: none;
`;
export default app;

This renders a customized styled button! At up to this step, we have not yet defined what the primary button would look like. We will do that in the next step:

To add conditional primary styles, import css helper:

import React from "react";
import styled, { css } from 'styled-components';
const Button = styled.button`
  {/* Base styles */}
  ${(props) =>
    props.$primary &&
    css`
      background: #ff4385;
      color: white;
    `
  }
`;

Here the primary variant overrides colors.

In this code snippet above ⬆, we defined what a primary button looks like.

To do that we also import { css } from styled-components and interpolate a function into our template literal, which gets passed the props of our component:

Our final new component will then be:

import "./styles.css";
import styled, { css } from "styled-components";
export default function App() {
  return (
    <div className="App">
      <Container>
        <Button>Normal Button</Button>
        <Button $primary>Primary Button</Button>
      </Container>
    </div>
  );
}
const Button = styled.button`
  background: transparent;
  border-radius: 3px;
  border: 2px solid #ff4385;
  color: #ff4385;
  margin: 0.5em 1em;
  padding: 1rem 2rem;
  text-decoration: none;
  ${(props) =>
    props.$primary &&
    css`
      background: #ff4385;
      color: white;
    `}
`;
const Container = styled.div`
  text-align: center;
  display: inline-block;
`;
export default app;

We are using an arrow function to pass in the props and apply dynamic styles that are based on props. Also with ES6, we can now create functions without the function keyword, instead, we use arrows (=>), thereby termed arrow functions. With arrow functions, we can write functions in one line without the return keyword or braces ({}) around it.

This shows how reusable styled components can cleanly abstract and extend styles! As you can see, styled-components let 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.

The Styled Components as Property

Use the as prop in styled-components to make a component act like a different HTML tag. This allows for flexible usage of components.

The as prop provides a way to make a styled component render as a different HTML tag or React component while retaining its defined styles. This enables the flexible reuse of styles for multiple elements.

A common example is building a navigation bar with a mix of links and buttons that should appear visually consistent.

Rather than duplicating styles across individually styled components, the as property allows dynamically switching the underlying element for a single defined and shared styled component.

For instance, a NavButton styled component could be created for standard navigation button styling, then conditionally rendered as needed either as a button or a (anchor tag) link while always keeping the NavButton CSS styles applied through the power of as. This avoids needing to redefine styles just for alternate elements. To make this a working link we would need an href attribute.

This code snippet below demonstrates how to use anchor tag (a) as a button.

import "./styles.css";
import styled, { css } from "styled-components";
export default function App() {
  return (
    <div className="App">
      <Container>
        <Button>Normal Button</Button>
        <Button $primary>Primary Button</Button>
        <Button as="a" href="#">
          Link with Button styles
        </Button>
        <DarkButton as="a" href="#">
          Link with Dark Button styles
        </DarkButton>
      </Container>
    </div>
  );
}
const Button = styled.button`
  background: transparent;
  border: 1px solid #ff4385;
  border-radius: 3px;
  border: 2px solid #ff4385;
  color: #ff4385;
  margin: 0.5em 1em;
  padding: 1rem 2rem;
  ${(props) =>
    props.$primary &&
    css`
      background: #ff4385;
      color: white;
    `}
`;
const Container = styled.div`
  text-align: center;
  display: flex;
  flex-wrap: wrap;
  justify-content: center;
`;
const DarkButton = styled(Button)`
  color: #666666;
  border-color: #666666;
`;
export default app;

In the example above, the <Container />serves as a wrapper component for other component such as our custom component for Button, DarkButton.

How to Apply Media Queries using Styled-Components

Media queries are essential in React projects for responsive designs. Styled components enable component-scoped media queries for centralized breakpoint logic.

const Header = styled.header`
  padding: 10px;
  @media (min-width: 768px) {
    display: flex;
    justify-content: space-between;
    li {
      display: inline-block;
    }
  }
`;
function App() {
  return (
    <Header>
      <h2>Site Title</h2>
      <ul>
        <li>Item 1</li>
        <li>Item 2</li>
      </ul>
    </Header>
  );
}
export default app;

In this code snippet above, the mobile styles are defined first, and then a media query overrides them for larger screens via Flexbox, etc.

Scoping breakpoints per component keeps concerns separated. Changes stay isolated from unrelated styled elements. Debugging layout issues also focuses only on the relevant component.

The styled-components framework cleanly integrates media queries for component-based responsive UIs.

How to Create Global Styles with Styled Components

The styled-components library focuses on component-level CSS scoping. But what if we need global styling resets/defaults?

Let’s use the createGlobalStyle helper to define application-wide rules.

First, make a globalStyles.js file:

// globalStyles.js
import { createGlobalStyle } from 'styled-components';
const GlobalStyle = createGlobalStyle`
  body {
    margin: 0;
    padding: 0;
    background: teal;
    font-family: Open-Sans;
  }
`;
export default GlobalStyle;

Then, import this in the root component:

// App.js
import GlobalStyle from './globalStyles';
function App() {
  return (
    <>
      <GlobalStyle />
      <OtherComponents/>
    </>
  );
}

The key thing is that GlobalStyle must be a sibling of the app’s top-level components to work.

For example:

return (
  <>
    <GlobalStyle />
    <Navbar />
    <Content>
      // Rest of the app
    </Content>
  </>
)

Now global styles are applied app-wide from that single GlobalStyle component!

FAQs

What are the benefits of using styled-components in React apps?

Styled components allow you to write CSS code in your JavaScript files to style React components. Benefits include easier organization, scoping styles, dynamic styling, and more.

Are styled components necessary for styling React apps?

No, styled components are not required. You can use traditional CSS or other CSS-in-JS libraries. But styled components are a popular and useful option.

How do styled components compare to options like Tailwind CSS?

Tailwind is a utility-first CSS framework, while styled components let you write actual CSS. Tailwind can be faster to develop with, but styled components give more customization.

What are some key features of styled-components?

Key features include writing CSS-in-JS, scoped styling, using JavaScript capabilities for dynamic styling, and themes, easier reuse of styles, and simplified organization.

How do you use styled-components with JSX style syntax?

The css prop allows passing styles as a JS object. Import ‘styled-components/macro’ to enable the css prop and JSX style syntax for styled-components.

What You Have Learned

In this article, through step-by-step guidance, you have scaffolded a fully configured React project leveraging modern toolchains. You now understand how a React codebase organizes by compartmentalizing concerns into modular discrete directories like /src for component logic and /public for static dependencies.

Additional subdivision into styles, utils, and components clarifies the app’s functional areas as complexity increases.

You now understand how to leverage the styled-components library to create reusable UI components with co-located and encapsulated styling rules defined using actual CSS code within JavaScript. Tagged template literals provide a mechanism to inline styles scoped specifically to that component, avoiding conflicts with global stylesheets through automatically generated class names for isolation.

Conditional styling modifiers can be applied based on props rather than class name conventions, leading to greater transparency within the component interface itself for its different style variations.

By externalizing presentational definitions, concerns get separated and components become more portable and platform-agnostic.

Implementation details were covered for applying global stylesheet resets or defaults using the createGlobalStyle construct to complement the component-based styling architecture.

Integration at the root app level allows the global styles to permeate all nested UI components uniformly.

If you want to learn more, check out this complete course on Styled components by Traversy Media on YouTube:

Check out how Purecode.ai has revolutionized the way web applications are developed. You no longer have to go through the hassle of writing a piece of code for every component of your website or web application, just choose from our repository of 10,000+ AI-generated custom components. Try it now 🚀

Happy Coding 💻

Further Readings

If you enjoyed reading this piece, consider reading these articles, too:

Emmanuel Uchenna

Emmanuel Uchenna

Emmanuel is an experienced and enthusiastic software developer and technical writer with 4+ proven years of professional experience. He focuses on full-stack web development. He is fluent in React, TypeScript, VueJS, and NodeJS and familiar with industry-standard technologies such as version control, headless CMS, and JAMstack. He is passionate about knowledge sharing.