DEV Community

Cover image for Intro to Styled-Components
💅...
Adyasha Mohanty
Adyasha Mohanty

Posted on • Updated on • Originally published at adyablogs.tech

Intro to Styled-Components 💅...

Styled-Components💅 is the leading framework in CSS-in-JS libraries all over the world. They are easy to integrate into existing applications that are using other methods of styling.
By focusing on a single use case we managed to optimize the experience for developers as well as the output for end users.

The main reason for this popularity is that: finally, we can use the power of JavaScript inside our stylesheets💪.

power

The easiest way we can modify styles with JavaScript is using inline styles. It is not super efficient and even elegant, but it is absolutely legal and the greatest benefit of this technique is that the styles will be encapsulated in the scope of the component.

React supports inline styles from the beginning of its existence so it can be a way of creating styles in React applications⚛️.

Note: Styled components are available both for React and React Native, and while you should definitely check out the React Native guide, our focus here will be on styled-components for React.

Installation⚙️

Styled-Components can be installed via NPM like almost everything else you need to develop with React.js.

npm i styled-components
or
yarn add styled-components

Starting Out🏃

Then you can import the library into React.js, and create our first styled component. Put these simple lines in your react code:

import styled from "styled-components";

// Styled component named StyledButton
const StyledButton = styled.button`
  background-color: black;
  color: red;
  font-size: 15px;
`;

function OurFirstComponent() {
  // any other component
  return <StyledButton> Login </StyledButton>;
}
Enter fullscreen mode Exit fullscreen mode

vscode-styled-components is a great extension for VS Code.

First of all, you have to import the styled function from styled-components package and after that, you can choose from the predefined set of HTML tags (the library supports them all) an interesting component to use.

The part of the code after the import statement looks like function invocation but here we have backticks 😮instead of brackets.

styled-components use one of the newest features from the_ES6 standard_ of JavaScript called tagged template literals.

So basically the code between backticks is a body of the button function.
Isn’t it look familiar 👀? Well, it should, because this is a regular CSS code with regular CSS syntax.

In raw HTML and CSS, we would have this:

button {
  background-color: black;
  color: red;
  font-size: 15px;
}

<button> Login </button>

Enter fullscreen mode Exit fullscreen mode

In short🤏: StyledButton is the styled component, and it will be rendered as an HTML button with the contained styles. styled is an internal utility method that transforms the styling from JavaScript into actual CSS.

And that is all! Incredibly easy to start with if you know CSS 😃. Let’s move further👉.

Passing props😉

Styled components are functional, so you can easily style elements dynamically.
Imagine you have two types of buttons on your page having different background colors and you are not allowed to make two different styled-components. Then What should you do 🤔?

In this case, we can adapt their styling based on their props. We can pass additional properties into a styled component in the same way you pass them in other React components:

import styled from "styled-components";

const StyledButton = styled.button`
  border: none;
  min-width: 300px;
  font-size: 15px;
  padding: 6px 8px;
  /* the resulting background color will be based on these props */
  background-color: ${props => props.bg === "black" ? "black" : "red";
`;

function BackgroundComponent() {
  return (
    <div>
      // Use of different props
      <StyledButton bg="black"> Button1 </StyledButton>
      <StyledButton bg="red"> Button2 </StyledButton>
    </div>
  )
}
Enter fullscreen mode Exit fullscreen mode

Here, StyledButton is a React component that accepts props, we can assign a different background color based on the existence or value of the bg prop. Isn't it cool 😎?

Cool Image

More Features✍️

The examples which I presented are really simple and basic, but styled-components has more useful features including:

  • Theming – Styled-components provides theming capabilities and enables you to support multiple looks and feels.

  • Nested rules – If you are familiar with SASS or LESS preprocessor you know how nesting rules can be useful. With styled-components, it is possible too.

  • Scoped selectors – You don’t have to think about naming conventions to avoid selector collisions on your pages.

  • Dead code elimination – Styled-components has an optional configuration to remove code that does not affect the program results.

  • Global Styling - The styled-components framework also enables you to create global styles to be applied to all styled-components.

  • Server-side rendering support – By using ServerStyleSheet object and StyleSheetManager you can utilize all styles from the client-side and returns them from the server-side.

  • Stylelint support – Good real-time linting is priceless when you have to debug your styles.

  • Use with other CSS frameworks – You can use styled-components with any CSS framework like Material Design styled component.

As you can see, there are a lot of features that you can use while working with styled-components.

For more Information, the styled-components documentation is always a good place to go.

The idea behind styled-components can be really weird at the beginning of your journey but if you give it a try, you will love it 😍.

Thanks for Reading💙! Have a great day :)

Find me on Twitter @Adyasha805.
This post is also posted on my blog page.

Top comments (2)

Collapse
 
adityapadhikbl profile image
Aditya Padhi

Really nice write-up. Keep up the good work.

Collapse
 
adyasha8105 profile image
Adyasha Mohanty

Thanks, dear :)