Why styled-components in React

As an introduction of style-components I as that styled-components is a massively growing community around with over 22,000 on GitHub, mostly coming from React developers, which is very encouraging and speaks to the prospects of longevity.

Styled components are a CSS-in-JS tool that bridges the gap between components and styling, offering numerous features to get you up and running in styling components in a functional and reusable way. In this article, you’ll learn the basics of styled components and how to properly apply them to your React applications.

Reasons to use styled-components:

Performance improvements

Styled components keep track of which components are rendered on a given page and inject their styles and nothing else. This means your user loads the least amount of styles necessary for a given component.

Reusable components

Styled components allow us to create components that are extremely easy to reuse as they directly contain their style values.

Some of the following JSX:

  
    <h1 className="title" > G Soft </h1>

can be translated in the following component:


    const Title=styled.h1`
      color:white;
      font-size:3rem;
    `

And ca be used like so:

    <Title>G Soft<Title>

No -class policy:

Styled-components enforces the use of props in the place of classes. This no-class policy has helped them make more developers tow the route of best practices for controlling the behavior of a component.

Initially, you would write:

    
    <h2 className="title primary"> Hello world </h2>

    h2.Subtitle{
      font-size : 2em;
      color : green;

    &.primary{
       color : red;
       }
    }

but now , it should be like this:


    const Subtitle= styled.h2`
      font-size : 2em;
      color : ${ props=>props.primary ? 'red' : 'green' };
    `;
  
  <Subtitle primary> Hello World <Subtitle>