Using scoped classes in "styled-components"

After a lot of practice in migrating components from sass to styled-components and quite a few trials and errors I feel that the following is least painfull: Declaring scoped classes (much like sass) in the styled component.

.component

    > svg
        width: 39px
        fill: #ababb2

    .title
        font-size: $gi-font-size-x-extra-jumbo
        font-weight: $gi-font-weight-extra-normal
        padding: 20px 0

    .details
        font-size: $gi-font-size-semi-large
        padding: 5px 0

    button
        margin-top: 40px

Becomes this:

import styled from 'styled-components';
import { giTheme } from '../themes';

const Container = styled.div`
    svg {
        width: 39px;
        fill: #ababb2;
    }

    & .title {
        font-size: ${giTheme.giFontSizeXExtraJumbo};
        font-weight: ${giTheme.giFontWeightExtraNormal};
        padding: 20px 0;
    }

    & .details {
        font-size: ${giTheme.giFontSizeSemiLarge};
        padding: 5px 0;
    }

    button {
        margin-top: 40px;
    }
`;

export default {
    Container,
};

The space between the ampersand and the class name indicated that it is a class declaration The Component’s code stays pretty much the same:

The usage is just like regular classes: <div className="title" >...</div>

Notice that the classes are plainly refered to as className=”title”. in the rendered code it will show up as

.hctASO .title {
    font-size: 2.6rem;
    font-weight: 500;
    padding: 20px 0;
}

** this class is scoped to the container and not to the entire page :) **

I like it because it reduces the number of styled components you need to create - no more “component per class”… I hope this helps! Further reference here: https://github.com/cssinjs/jss-nested

Javascript Architect

Frontend Group

Thank you for your interest!

We will contact you as soon as possible.

Want to Know More?

Oops, something went wrong
Please try again or contact us by email at info@tikalk.com
Thank you for your interest!

We will contact you as soon as possible.

Let's talk

Oops, something went wrong
Please try again or contact us by email at info@tikalk.com