Styled Components (CSS-In-JS)

7th July 2023

styled-component-banner

Introduction

When it comes to styling components in web development, there are several ways to do so. One popular approach is to use CSS (Cascading Style Sheets) to apply styles to HTML elements. However, there are other approaches that offer more advanced features and benefits.

In this blog, we will focus on styled-components, a library for styling React components that has gained popularity in recent years.

What is styled-component?

Styled-components is a library for React that allows you to write CSS code directly inside your JavaScript components.

It uses tagged template literals to define styles, which are then parsed and injected as CSS into the page.

Styled-components provides a way to encapsulate styles and reduce global namespace pollution, making it easier to maintain and reuse styles across different components.

Why styled-component?

Styled-components offer several advantages over traditional CSS styling:

a. Encapsulation: Styles defined with styled-components are encapsulated within the component, meaning they do not leak out and affect other elements on the page. This makes it easier to manage and maintain styles, especially in larger projects.
b. Dynamic styles: Styled-components allow you to create dynamic styles based on props or other factors. This can be useful for creating responsive designs or for applying different styles based on user interactions.
c. Theming: With styled-components, you can define a theme object that can be passed down to all components in the tree, allowing for consistent styling across the application. Styled Components (CSS-In-JS) 2
d. Code organization: By keeping styles and components in the same file, you can improve code organization and reduce clutter in your project.

Setup styled-component in React Project (with Example)

To use styled-components in your project, you first need to install it as a dependency. You can do this using npm or yarn:

        #with npm
          npm install styled-components
          #with yarn
          yarn add styled-components
      

Once installed, you can import the library in your React component and use it to define styles:

        import styled from 'styled-components';
          const Button = styled.button`
          background-color: ${props => props.primary ? 'blue' : 'white'};
          color: ${props => props.primary ? 'white' : 'black'};
          font-size: 16px;
          padding: 10px;
          border: none;
          border-radius: 5px;
          `;
          function App() {
          return (
          <>
          
          
          
          );
          }
      

In this example, we define a Button component using the styled function. The component is defined as a button element with some CSS styles applied to it.

We use template literals to define the styles, which allow us to interpolate JavaScript expressions using the ${} syntax. We also define some dynamic styles based on the props passed to the component.

How styled-components work under the hood?

Styled-components works by generating unique class names for each component and injecting the CSS styles as a style tag in the page header. This ensures that styles are scoped to the component and do not affect other elements on the page. The library uses a combination of CSS-in-JS techniques and the CSSOM (CSS Object Model) to generate and apply styles. When you define a styled-component, it creates a new class name and adds the styles to a style sheet object. When the component is rendered, the library generates a new class name and attaches it to the component, ensuring that the styles are only applied to that specific instance of the component. Styled-components also offers advanced features like server-side rendering, theming, and global styles. These features are implemented using various techniques like CSS variables, dynamic style generation, and more.

How to implement dark and light mode?


            const Button = styled.button`
background-color: ${props => props.theme.background};
color: ${props => props.theme.color};
font-size: 16px;
padding: 10px;
border: none;
border-radius: 5px;
`;
const theme = {
light: {
background: '#ffffff',
color: '#000000'
},
dark: {
background: '#000000',
color: '#ffffff'
Styled Components (CSS-In-JS) 4
}
};
function App() {
const [isDarkMode, setIsDarkMode] = useState(false);
const handleToggleTheme = () => {
setIsDarkMode(prevMode => !prevMode);
};
return (

This is some sample text.

); }

In this example, we define a Button component that uses a theme object to define its styles. We define the theme object with two properties: light and dark , which represent the light and dark modes of the app, respectively. We use the useState hook to keep track of the current mode ( isDarkMode ) and define a function ( handleToggleTheme ) to toggle the mode when the Button component is clicked. We wrap our app component in a ThemeProvider component from styled-components, passing in either the light or dark theme object based on the isDarkMode state. This makes the theme available to all styled-components within the app. Finally, we render the Button component, which toggles the theme when clicked, and some sample text to demonstrate how the theme affects the styles of other components. With this setup, we can easily switch between light and dark modes by clicking the Toggle theme button. This makes theming with styled-components a powerful and flexible way to manage the look and feel of your app, especially when it comes to supporting multiple color schemes.