An Explanation: Styled components for Beginners

An Explanation: Styled components for Beginners

Introduction

Welcome! If you're new to web development, you might be familiar with CSS and the different ways you can use it to style your websites. But do you know what styled-components are? styled components is a library that allows us create reusable and modular styles in our react applications. We'll go over the fundamentals of styled components in this article and show you how they can help you create visually appealing styles for your projects. Let's dive in!

What is styled-components

Styled-components is the result of wondering how we could enhance CSS for styling React component systems. By focusing on a single use case we managed to optimize the experience for developers as well as the output for end users.

Apart from the improved experience for developers, styled-components provides:

  • Automatic critical CSS: styled-components keeps track of which components are rendered on a page and injects their styles and nothing else, fully automatically. Combined with code splitting, this means your users load the least amount of code necessary.

  • No class name bugs: styled-components generates unique class names for your styles. You never have to worry about duplication, overlap or misspellings.

  • Easier deletion of CSS: it can be hard to know whether a class name is used somewhere in your codebase. styled-components makes it obvious, as every bit of styling is tied to a specific component. If the component is unused (which tooling can detect) and gets deleted, all its styles get deleted with it.

  • Simple dynamic styling: adapting the styling of a component based on its props or a global theme is simple and intuitive without having to manually manage dozens of classes.

  • Painless maintenance: you never have to hunt across different files to find the styling affecting your component, so maintenance is a piece of cake no matter how big your codebase is.

  • Automatic vendor prefixing: write your CSS to the current standard and let styled-components handle the rest.

You get all of these benefits while still writing the CSS you know and love, just bound to individual components.

Installation

Using JavaScript-written CSS styles, Styled Components is a library that enables you to style your React components. Because it helps to keep your styles modular and co-located with your components, it is a common option for styling in React applications. This can make your code simpler to comprehend and maintain.

You must use npm or yarn to add styled components as a dependency in order to install them in your React project. Run this command after opening a terminal and going to your project directory:

# with npm
npm install --save styled-components

or

# with yarn
yarn add styled-components

This will install styled components and add it to your project's dependencies.

After installing styled components, you can use them in your project by importing them into your component library and creating styled components with the styled function.

Getting Started

The styled-components module uses template literal tags to style components.

It removes the mapping between components and styles. In other words, when you define your styles, you're actually creating a React component that has your styles attached.

Here is an example of how you might use styled components to style a simple button component:

import styled from 'styled-components';

const Button = styled.button`
  background-color: red;
  border: none;
  padding: 10px;
  color: white;
  font-size: 30px;
`

const Example1 = () => {
 return (
    <Button>Click me</Button>
  );
};

output:

In this example, we have created a styled button element that has a red background, white text, and some basic styling applied to it. You can then use this styled component in your application just like any other React component.

The syntax

Using JavaScript-written CSS styles, Styled Components is a package that enables you to style your React components. Because it employs declarative syntax, you may directly express your styles in the component code, which can make them more modular and simpler to manage.

The basic syntax for creating a styled component with styled components looks like this:

import styled from 'styled-components';

const MyStyledComponent = styled.div`
  /* your styles go here */
`;

In this example, we are creating a styled component called MyStyledComponent that is based on a div element. You can replace the div with any other valid HTML element, such as a button, input, or a.

Inside the template literal, you can write your CSS styles as you would normally. The styles will be applied to the element when the styled component is rendered.

Here is an example of a styled component with some basic styles applied:

import styled from 'styled-components';

const MyStyledComponent = styled.div`
  background-color: blue;
  border: none;
  padding: 10px;
  color: white;
  font-size: 30px;
`;

output

You can also use JavaScript expressions inside your template literal to make your styles more dynamic. For example, you can use props to control the styles of your component based on the values passed to it.

In the following sections, we'll discuss adding styles based on props.

Styling Component's Children

But will we need to construct a stylized component for each element if the component has child elements that also need to be styled? No, we may apply styles to child elements in a manner similar to this.

const Footer = styled.footer`
 display: flex;
  justify-content: space-evenly;
  align-items: center;
  padding: 10px 15px;
  background: gray;
  ul li{
   list-style-type: none;
  }
  h1{
  color: red;
  }
  input{
   padding: 10px;
   border: none;
   border-radius: 10px;
  }
`
const Example2 = () => {
 return (
 <Footer>
         <h1>Styles</h1>
         <ul>
            <li>hello</li>
            <li>hello</li>
            <li>hello</li>

         </ul>
         <ul>
            <li>hello</li>
            <li>hello</li>
            <li>hello</li>
         </ul>
          <ul>
            <li>hello</li>
            <li>hello</li>
            <li>hello</li>
         </ul>
         <input type="text" placeholder="hello" />
    </Footer>
    );
};

output:

You'll notice that the styles we added only affect the element in the Footer component

Using props with styled-components

You can pass props to a styled component and configure and alter your styles based on props

This button component has an active state that changes its background color. In this case, we will swap out the background of the active prop when we set it to true.

Here is an example of a styled component that uses props to change the background color based on the color prop:

const Button = styled.button`
  background: ${props => props.active ? "palevioletred" : "white"};
  font-size: 2em;
  margin: 1em;
  padding: 0.25em 1em;
  border: 2px solid palevioletred;
  border-radius: 3px;
`
const Example2 = () => {
 return (
   <>
    <Button active={true}>
      click me
     </Button>
      <Button>click me</Button>
     </>
  );
 };

Applying Pseudo-classes and Pseudo-elements

It is possible to apply pseudo-classes (e.g :hover) or/and pseudo-elements (e.g ::after) to a styled component. If we had a button to change the border color when hovered on, we would have.

const Button = styled.button`
  padding: 10px;
  border: 2px solid red;
  border-radius: 4px;

  &:hover {
    border-color: blue;
  }
`;

output

Extending styles

You may regularly want to use a component yet make a small adjustment for a specific instance. It would take a lot of work to pass in an interpolated function and update them based on some props.

To easily make a new component that inherits the styling of another, just wrap it in the styled() constructor. Using the button from the last section, we create a special one with some colour-related styling:

const Button = styled.button`
  color: palevioletred;
  font-size: 1em;
  margin: 1em;
  padding: 0.25em 1em;
  border: 2px solid palevioletred;
  border-radius: 3px;
`;

// A new component based on Button, but with some override styles
const TomatoButton = styled(Button)`
  color: tomato;
  border-color: tomato;
`;

output

Animations

In React applications, styled components are a popular technique to style components. They enable you to apply CSS styles you create in JavaScript to your components. The ability to fully utilize JavaScript to manipulate your styles over time makes this very helpful for animation creation.

You must define the phases of your animation using the keyframes method in order to build an animation with stylized components. You can then specify which keyframes to use and how to apply the animation using the animation property in your styled component.

Here is an example of how you might create a simple fading animation using styled components:

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

const slide = keyframes`
  0% { transform: translateX(0) }
  50% { transform: translateX(100%) }
  100% { transform: translateX(0) }
`;

const MovingButton = styled.button`
  padding: 10px;
  background: #f4f4f4;
  border: 2px solid red;
  border-radius: 4px;
  animation: ${slide} 2s ease-in-out infinite;
`;

In this example, we have defined a fadeIn keyframes animation that transitions the opacity of an element from 0 to 1 over the course of one second. We have then applied this animation to a styled div element using the animation property.

You can customize your animation further by specifying additional properties such as the duration, delay, and iteration count. You can also use JavaScript to control the animation, for example by using the animation-play-state property to pause or resume the animation.

Conclusion

Finally, styled components are an effective tool for creating reusable and modular styles in your React apps. They make it simpler to manage and maintain your styles as your project expands by enabling you to write your styles directly in your JavaScript code. You should now have a strong basis for utilizing styled components in your own applications after reading this guide's strategies and recommended practices. We sincerely hope that this introduction to styled components was useful, and we invite you to learn more about the various applications of styled components for developing appealing and enduring styles for your online projects.

You can also check out the styled-components official documentation to learn more.

As you continue to work with styled components, remember to keep things simple and focus on creating styles that are easy to understand and maintain. With a little practice, you'll be a pro at using styled components in no time!