Skip to main content

Command Palette

Search for a command to run...

Styled Components

_ at a glance _

Published
8 min read
Styled Components
R

I am a Front End Engineer / Developer.

STYLED COMPONENTS

A lot happens with the modern CSS and JS

A Styled Component is the combination of a DOM element and the rules that can style it.

In today’s JavaScript era, words like modules, components, functions, bundlers, transpliers, etc., are very popular and used widely. Components are very useful to develop scalable systems. An interesting feature that makes Styled Components more powerful is, CSS styles can be maintained as Components that can be reused at ease.

A Component

A Component is a popular term in the JavaScript World. Developers love to reuse their code whenever necessary instead of taking all pain to write it again. Component based Architectures are the robust way to solve a lot of issues in front-end engineering. Like native web components, a user defined css component is also possible but with a slightly different approach and with JavaScript/ES6 combination makes it possible.

1-Components-updated.jpg

Usually, a Component is a file with .js extension. A Class or a Function that can return something can behave like a component.

Now-a-days, CSSinJS is a popular term for components styling web elements and also for various other useful features.

Styled-Components

Styled-components is a library that makes the best use of CSS to style the Component based systems like React / ReactNative. ES6 standards play an important role in this aspect. The best part is we can use transpilers like Babel to make efficient use of this library. On the other hand, styled-components can be used easily along with other libraries.

Easy of use - Installation

First of all, like any other node based library or a framework, styled-components can be installed using npm or yarn. Use the following command in your terminal or CLI :

npm install --save styled-components
yarn add styled-components

CSS Components - the Basics

A Component is a code block that is wrapped with a reference name and can be reused. A CSS Component is a block of styles defined and can be reused in the form of a component which is a very flexible way to reduce the number of lines of css code.

Building Design Systems

2-DesignSystems-updated.jpg Building a design system is one of the sophisticated approaches to foresee and solve many problems in the Front End Architecture of a Scalable System. Such design systems can easily be used among various groups of designers and developers at no extra effort. A Design System plays a vital role in creating a better user experience and Styled Components comprise of many distinct features to create such a sophisticated system.

CSSinJS

The way of css styling web elements with JavaScript/es6 support takes css standards to the next level. This approach is very feasible for developers to use and to implement it in scalable products.

3-CSSinJS-updated.jpg

In general, CSS in JS refers to dynamic css, server side rendering, auto vendor fixes etc. Styled Components have features that cover everything of CSSinJS and moreover it gives you a feel of ReactJS.

Props play major role

Props / properties are nothing but arbitrary inputs of Components. These are helpful to create intuitive theming of components and developers can use them to enable dynamic styling of CSS. Furthermore, props can also be passed conditionally to a component. Like in react, props are available in styled components as well. 4-Props-updated.jpg
Code Sample:
Styles.js -->

import styled from "styled-components";

export const MsgText = styled.div`
 color: ${(props) => (props.danger ? "#db0000" : "#04a134")};
 font-size: 20px;
`;

App.js -->

<MsgText danger> You are not authorised to edit page...! </MsgText>
       <br />
<MsgText> But you can view it. </MsgText>

Conditioning Styles

5-Conditions-updated.jpg

While passing props to a styled component, conditions can be added based on which the output(styling) of that component changes when rendered in DOM. Using a ternary operator is the best and shortest way to add conditions to props’ values as shown in the image below:

Flexible CSS Components (Extend / Override)

Unlike normal css, styled components allow us to inherit styles from another. There is a constructor called styled( )which makes inheritance possible.
6-Extend-Overide-updated.jpg
Code Sample:
Styles.js -->

import styled from "styled-components";
export const MsgText = styled.div`
 color: ${(props) => (props.danger ? "#db0000" : "#04a134")};
 font-size: 20px;
`;

export const MsgGhost = styled(MsgText)`
color: ${(props) => (props.restricted ? "#adadad" : "#8b8b8b")};
`;

App.js -->

<MsgText> You can view it. </MsgText>
<MsgGhost restricted>This is Admin's Block.</MsgGhost>

Without disturbing the existing ones, overriding styles seems easy to use with the help of props. As shown in the above code sample, the styled( ) constructor modifies color property in MsgGhost that was inherited from MsgText and overrides its values with some props and conditions. Now, MsgGhost has updated color value and inherited font-size.
Eg:

Pseudo Selectors

8-SelectorPseudo-updated.jpg

Besides Sass and Less, Stylis is a light-weight css preprocessor. Styled Components library uses it to adapt nested styling, selector patterns etc. ‘&’ character makes different selector patterns possible, for example:

import styled from "styled-components";
export const Input = styled.input`
color:green;
&:hover { 
color:red; 
}
`;

In this code, &:hover represents the styles applied on hover of the input element. Similarly, we can make use of different selector patterns like we use in normal css, such as
&:focus
& + &
& ~ &
&.classname
&#id
...to mention a few.

Create Animations

‘Keyframes’ play an important role animating objects on DOM whether it is core css or any library/framework. It is the same case with Styled Components as well.

9-Keyframes-updated.jpg

Combining keyframes with attributes binding features allow us to create a number of various interesting animations on the Web. Any css property can be animated except those who have boolean values. In particular, css properties whose values vary in a particular range instead of fixed values, can be animated to get nice visual appeal. Code Sample:
Styles.js -->

import styled from "styled-components";

const blinkText = keyframes`
 0%{color:rgba(9,113,241,1)}
 25%{color:rgba(9,241,38,1)}
 50%{color:rgb(241,137,9,1)}
 100%{color:rgba(9,113,241,1)}
`;
export const AnimTextC = styled.div`
 font-size: 30px;
 line-height: 70px;
 font-weight: bold;
 max-width: 800px;
 margin: auto;
 border: 2px dotted #e5e5e5;
 animation: ${blinkText} 2s ease infinite;
`;

App.js -->

import { AnimTextC } from "./styles.js";
export default function App() {
 return (
    <div className="App">
        <AnimTextC>Text Viz</AnimTextC>
    </div>
)
}


Eg:

Theming

11-Theming-updated.jpg Styled Components have huge support for theming UI Layers. It is easy to use and it reduces repetitive styles. It can be done using a specific wrapper to theme a UI and can be reused and customised with no time. is a wrapper component to wrap UI with themes. For example,
App.js

import { ThemeProvider } from "styled-components";

const cyanTheme = {
 regular: "#588a93", hover: "#31808f"
};
const brownTheme = {
 regular: "#816c6c", hover: "#5e4848"
};

<ThemeProvider theme={cyanTheme}>
    <form>
             <div className=”title”>Fill the details</div>
              ……. …. .. ..     
    </form>
</ThemeProvider>
<ThemeProvider theme={brownTheme}>
    <form>
             <div className=”title”>Fill the details</div>
             ……. …. .. .. 
     </form>
</ThemeProvider>

Styles.js

.title { color: ${(props) => props.theme.regular}; }

Eg:

Attributes

10-Attr-updated.jpg The Styled Components library provides us the right way to decorate a component and make it more dynamic yet simple to use. .attrs( ) constructor is available that can do all the work. This kind of approach is more useful for scalable projects instead of the smaller ones. Have a look at a sample code:

const Anchor = styled.a.attrs((props) => ({
 href: props.yahoo
   ? "https://www.yahoo.com"
   : props.google
   ? "https://www.google.com"
   : ""
   ? "#"
   : props.href,
 target: "_blank"
}))`
 color: blue;
 font-size: 16px;
 padding: 7px;
 display: block;
`;

Go through this example to understand it thoroughly:

Decorating a Component

Styled Components library provides us the right way to decorate a component and to make it user friendly with the help of props, attrs, conditions, dynamic styling, extending / overriding the styles etc.

7-DecorateComponent-updated.jpg

A different type of prop is available which we can call it ‘Polymorphic’. Create a styled- component and we can render it as an html element as we desire. A keyword “as” is used like an attribute to make this happen, as shown below:

<button as=”a”>Click to open</button>

Here, a button tag will be rendered as an anchor tag as mentioned as=”a”. The value “a” refers to an anchor tag.

Refer this example for more details:

Similarly, a React Component can also be rendered as a styled-component by using polymorphic prop ‘as’.

... this is Styled-Components library at a glance. Still we can explore many interesting things when it is used along with any component based workflows like React.

...keep an eye for the next article on Package Managers.