HTML & CSS Course
HTML & CSS
/
Advanced

Styled Components

Definition

A popular library for React and React Native that allows you to use component-level styles in your application by mixing CSS directly inside JavaScript (CSS-in-JS).

Explain Like I'm New

Instead of creating a React `<button>` and giving it a CSS class, you use JavaScript to literally create a new React component called `<PrimaryButton>` that has the CSS physically baked into it. You write the CSS inside backticks (template literals) right in your JS file.

Real World Example

Passing JavaScript variables directly into the CSS. `<Button primary={true}>`. The CSS inside the component reads the `primary` prop and automatically turns the background blue.

Common Use Cases

  • •Highly dynamic React applications where styles change based on JS state

Interactive Example

/* 
  Note: This is a conceptual example of Styled Components in React.
  npm install styled-components
*/

/*
import styled from 'styled-components';

// 1. Create a styled component!
// It's a React component that renders an <a> tag with baked-in CSS.
const StyledLink = styled.a`
  color: ${props => props.primary ? 'white' : 'blue'};
  background: ${props => props.primary ? 'blue' : 'white'};
  padding: 10px 20px;
  border-radius: 4px;
  text-decoration: none;
  
  /* You can even nest hover states! */
  &:hover {
    opacity: 0.8;
  }
`;

export default function App() {
  return (
    <div>
      {/* 2. Use it like a normal React Component! */}
      <StyledLink href="#">Normal Link</StyledLink>
      
      {/* Because it's JS, the CSS reads the 'primary' prop dynamically! */}
      <StyledLink href="#" primary>Primary Link</StyledLink>
    </div>
  );
}
*/

<div>See the source code to view the React implementation!</div>

Interview Questions

basic

  • What pattern is Styled Components known for: CSS-in-JS or CSS Modules?

intermediate

  • How does Styled Components prevent class name conflicts?

Flash Cards

Question

Which pattern?

Click to reveal answer
Answer

CSS-in-JS.

Question

Prevent conflicts?

Click to reveal answer
Answer

Just like CSS Modules, it automatically generates random, unique class names (like `sc-bdvvtL gZMQgI`) for every component at runtime.