DEV Community

Cover image for Basics of Styled-Components
John Finley
John Finley

Posted on

Basics of Styled-Components

Styled-Components is a JavaScript library for styling React components by allowing you to write CSS code as JavaScript. It's main goal is to simplify and enhance styling in React apps. In this blog, I want to dive into the basics of styled-components and give you the confidence to use it in your own project.

Instead of defining styles in separate CSS files or using complex class names, styled-components encourages you to write your styles as tagged template literals in JavaScript. This means you can create components with their styles encapsulated, making your code more modular and maintainable.

Getting Started:

Begin by installing styled-components in your React project using npm or yarn:

npm install styled-components
# or
yarn add styled-components
Enter fullscreen mode Exit fullscreen mode

After installation you can import it into your components like this:

import styled from 'styled-components';
Enter fullscreen mode Exit fullscreen mode

Now, you're ready to start styling your components.

How It Works:

Styled-components uses tagged template literals, a feature of ES6 JavaScript. You can define a styled component by calling the styled function and passing in a template string. Here's a simple example using a button:

const Button = styled.button`
  background-color: #3498db;
  color: white;
  border: none;
  border-radius: 4px;
  padding: 10px 20px;
  cursor: pointer;
`;

const MyComponent = () => {
  return (
    <div>
      <Button>Click me</Button>
    </div>
  );
};
Enter fullscreen mode Exit fullscreen mode

In the code above, we've created a component named Button with styles defined directly within the backticks. The resulting Button component can be used like any other React component, and the styles will be automatically applied. Now that we know how to get started, let's take a look at some more syntax that you can use.

Additional Styled-Components Syntax:

Dynamic Styles with Props:

const Button = styled.button`
  background-color: ${(props) => (props.primary ? 'blue' : 'gray')};
  color: white;
  padding: 10px 20px;
`;

const MyComponent = () => {
  return (
    <>
      <Button primary>Click me!</Button>
      <Button>Click me also</Button>
    </>
  );
};
Enter fullscreen mode Exit fullscreen mode

The above allows you to use a primary prop in your button component to determine the background color. This is useful if you need dynamic styling that depends on different state. The button that has a primary prop will be blue. The button without will be gray.

Extending Styles:

const PrimaryButton = styled(Button)`
  background-color: blue;
`;
Enter fullscreen mode Exit fullscreen mode

Using the styled(element) syntax allows you to extend styles from already defined components. You can even do this with styled-components you've already made so that you don't have to double up on styles.

Global Styles:

import { createGlobalStyle } from 'styled-components';

const GlobalStyle = createGlobalStyle`
  body {
    margin: 0;
    padding: 0;
    overflow-x: hidden;
    font-family: 'Source Sans Pro', sans-serif;
}
`;
Enter fullscreen mode Exit fullscreen mode

GlobalStyle returns a StyledComponent that does not accept children. Place it at the top of your React tree and will inject the styles when the component is rendered.

Media Queries:

const Container = styled.div`
  width: 100%;
  padding: 20px;

  @media (min-width: 768px) {
    width: 50%;
  }
`;
Enter fullscreen mode Exit fullscreen mode

Keyframe Animations:

import styled, { keyframes } from 'styled-components';

const spin = keyframes`
  from {
    transform: rotate(0deg);
  }
  to {
    transform: rotate(360deg);
  }
`;

const Spinner = styled.div`
  width: 50px;
  height: 50px;
  border: 4px solid #3498db;
  border-top: 4px solid #3498db;
  border-radius: 50%;
  animation: ${spin} 2s linear infinite;
`;
Enter fullscreen mode Exit fullscreen mode

Theming with ThemeProvider:

import { ThemeProvider } from 'styled-components';

const theme = {
  primaryColor: 'blue',
  secondaryColor: 'green',
};
Enter fullscreen mode Exit fullscreen mode

Use ThemeProvider to pass themes

ReactDOM.render(
  <ThemeProvider theme={theme}>
    <App />
  </ThemeProvider>,
  document.getElementById('root')
);
Enter fullscreen mode Exit fullscreen mode

You will now be able to access the theme passed into ThemeProvider inside of all the nested styled-components no matter how many levels deep are there. Access the theme inside of your styled-component by using the dynamic styling syntax above.

Above I've shown you the basics of styled-components and how to get started. Styled-components provides a flexible and robust way to manage styling in React applications, making it a valuable tool for modern web development. I've really enjoyed using it in my projects and I hope that you will too!

Top comments (0)