Article image Styled Components: CSS in JS

42. Styled Components: CSS in JS

Page 86 | Listen in audio

Styled Components is a library for React and React Native that allows you to use component-level styles in your application. It is a popular CSS-in-JS tool that enables developers to write traditional CSS syntax within JavaScript files. This approach can make styling more dynamic and modular, aligning well with the component-based architecture of React.

The core idea behind Styled Components is to create small, reusable components with their own encapsulated styles. This encapsulation ensures that styles are scoped to the component, preventing issues like global CSS conflicts. By using Styled Components, you can manage styles in a more organized and maintainable way, particularly in large applications.

To get started with Styled Components, you need to install the library. You can do this using npm or yarn:

npm install styled-components
yarn add styled-components

Once installed, you can start creating styled components. Styled Components uses tagged template literals to style components. Here's a simple example:

import styled from 'styled-components';

const Button = styled.button`
  background-color: blue;
  color: white;
  font-size: 16px;
  padding: 10px 20px;
  border: none;
  border-radius: 5px;
  cursor: pointer;

  &:hover {
    background-color: darkblue;
  }
`;

In this example, a styled button component is created with specific styles. The component can be used in your React application just like any other React component:

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

One of the key benefits of Styled Components is the ability to leverage props to dynamically adjust styles. This makes it easy to create variations of a component without duplicating code. Here's how you can use props to change the button's color:

const Button = styled.button`
  background-color: ${props => props.primary ? 'blue' : 'gray'};
  color: white;
  font-size: 16px;
  padding: 10px 20px;
  border: none;
  border-radius: 5px;
  cursor: pointer;

  &:hover {
    background-color: ${props => props.primary ? 'darkblue' : 'darkgray'};
  }
`;

In this case, the primary prop controls the button's color. You can use this component like so:

function App() {
  return (
    <div>
      <Button primary>Primary Button</Button>
      <Button>Secondary Button</Button>
    </div>
  );
}

Styled Components also supports theming, which allows you to define a set of styles that can be applied across your application. This is useful for maintaining a consistent look and feel. To use theming, you need to define a theme and wrap your application with the ThemeProvider:

import { ThemeProvider } from 'styled-components';

const theme = {
  colors: {
    primary: 'blue',
    secondary: 'gray',
  },
};

function App() {
  return (
    <ThemeProvider theme={theme}>
      <Button primary>Primary Button</Button>
      <Button>Secondary Button</Button>
    </ThemeProvider>
  );
}

Then, you can access the theme values within your styled components:

const Button = styled.button`
  background-color: ${props => props.theme.colors.primary};
  color: white;
  font-size: 16px;
  padding: 10px 20px;
  border: none;
  border-radius: 5px;
  cursor: pointer;

  &:hover {
    background-color: darkblue;
  }
`;

Another powerful feature of Styled Components is the ability to extend styles. This is particularly useful when you want to create a new component based on an existing one with some additional styles:

const LargeButton = styled(Button)`
  font-size: 20px;
  padding: 15px 30px;
`;

In this example, LargeButton inherits all the styles from Button and adds its own modifications. This promotes reusability and helps keep your styles DRY (Don't Repeat Yourself).

Styled Components also supports global styles, which can be useful for setting up base styles or CSS resets. You can define global styles using the createGlobalStyle helper:

import { createGlobalStyle } from 'styled-components';

const GlobalStyle = createGlobalStyle`
  body {
    margin: 0;
    font-family: Arial, sans-serif;
  }
`;

function App() {
  return (
    <>
      <GlobalStyle />
      <Button primary>Primary Button</Button>
      <Button>Secondary Button</Button>
    </>
  );
}

In this example, GlobalStyle sets some base styles for the body element. The global styles are applied when GlobalStyle is rendered within the component tree.

Styled Components also integrates well with other CSS-in-JS solutions and tools, providing flexibility in how you manage styles in your React applications. Additionally, it offers server-side rendering support, which can be beneficial for SEO and performance optimization.

In conclusion, Styled Components is a powerful tool for managing styles in React applications. Its component-based approach aligns well with React's architecture, and its features like theming, dynamic styling, and style encapsulation make it a compelling choice for developers looking to build scalable and maintainable applications. By leveraging the full power of JavaScript, Styled Components allows for a more expressive and flexible styling experience, enhancing the overall development workflow.

Now answer the exercise about the content:

What is one of the key benefits of using Styled Components in React applications?

You are right! Congratulations, now go to the next page

You missed! Try again.

Article image Emotion: A CSS-in-JS Library

Next page of the Free Ebook:

87Emotion: A CSS-in-JS Library

5 minutes

Earn your Certificate for this Course for Free! by downloading the Cursa app and reading the ebook there. Available on Google Play or App Store!

Get it on Google Play Get it on App Store

+ 6.5 million
students

Free and Valid
Certificate with QR Code

48 thousand free
exercises

4.8/5 rating in
app stores

Free courses in
video, audio and text