SoFunction
Updated on 2025-04-11

js class library styled-components quick start tutorial

What is styled-components?

styled-components is a commonly used css in js class library. Like all class libraries of the same type, the capabilities that native css does not have are solved through js empowerment, such as variables, loops, functions, etc.

What are the advantages over other preprocessing?

  • Preprocessing such as sass&less can solve some of the limitations of css, but it still needs to learn new syntax and compile it. Its complex webpack configuration is always resistant to developers.
  • If you have experience in sass&less, you can quickly switch to styled-components, because most syntaxes are similar, such as nesting, & inheritance, etc. styled-componens solves the learning cost and development environment problems well, and is very suitable for project development of React technology stack && React Native.

What problems have been solved?

  • The writing method of className will make the original writing method of css very difficult to accept
  • If the import of css will cause the variable to leak globally, you need to configure webpack to make it modular
  • And the above mentioned solves the capabilities that native css does not have, which can accelerate the rapid development of projects

Official Documentation

/docs

Install

npm install --save styled-components

Editor Smart Tips

Updated on 2018-06-11

  • Webstorm requires the styled-component plugin to be installed
  • VScode has supported smart prompts

The most basic use

import styled from 'styled-components'
const Title = styled.h1`
    font-size: 1.5em;
    text-align: center;
    color: palevioletred;
`;
// equivalent to const Title = styled.h1(xx)const Wrapper = `
    padding: 4em;
    background: papayawhip;
`;
    render () {
        return (
            <Wrapper>
                <Title>Hello styled-components</Title>
            </Wrapper>
        )
    }

At this time, we can see that a random className is output in the console, which is done by styled-components for us. Note: The component name should start with a larger one, otherwise it will be parsed into a normal label.

Pass props

const Button = `
    background: ${props =>  ? 'palevioletred' : 'white'};
    color: ${props =>  ? 'white' : 'palevioletred'};
    font-size: 1em;
    margin: 1em;
    padding: 0.25em 1em;
    border: 2px solid palevioletred;
    border-radius: 3px;
`
render(
    <div>
        <Button>Normal</Button>
        <Button primary>Primary</Button>
    </div>
);

All props passed by components can be obtained when defining components, so it is easy to customize certain style components

Advanced usage of props

Set the default value. If the value must be passed, we will give a default value (defaultProps)

export default class ALbum extends  {
    constructor (props) {
        super(props)
         = {
            // Receive passed values            imgSrc: 
        }
    }
    render () {
        const {imgSrc} = 
        return (
            &lt;Container imgSrc={imgSrc}&gt;
            &lt;/Container&gt;
        )
    }
}
// You can get props hereconst Container = `
    background-size: cover;
    background-image: url(${props =&gt;  });
    width: 100%;    
    height: 300px;
`
// Of course, it doesn't matter if you don't pass the value. Let's set the default value = {
    imgSrc: Cover
}

Shaping components

This is very useful. You may encounter some components that are already components, but you need to add some styles to them. What should you do at this time?

// Pass className To use style in react-nativeconst Link = ({className , children}) =&gt; (
    &lt;a className={className}&gt;
        {children}
    &lt;/a&gt;
)
const StyledLink = styled(Link)`
    color: palevioletred;
`
render(
    &lt;div&gt;
        &lt;Link&gt;Normal components&lt;/Link&gt;
        &lt;StyledLink&gt;Is there any color?&lt;/StyledLink&gt;
    &lt;/div&gt;
);

Component style inheritance

const Button = `
    color: palevioletred;
    font-size: 1em;
    margin: 1em;
    padding: 0.25em 1em;
    border: 2px solid palevioletred;
    border-radius: 3px;
`;
const TomatoButton = `
    color: tomato;
    border-color: tomato;
`;
// TomatoButton Partial styles inherit from Button In this case, two classes will not be generated

Change component labels

In the idle situation, we want to change the label of the component, such as turning the button into a label

// Use the Button component defined above to call the withComponent methodconst Link = ('a')

Maintain other properties

In some cases, we may need to use third-party library styles, which we can easily achieve using this method

const Input = ({
    // Define static props    type: 'password',
    // Use 1em by default if no transmission    margin: props =&gt;  || '1em',
    padding: props =&gt;  || '1em'
})`
    color: palevioletred;
    font-size: 1em;
    border: 2px solid palevioletred;
    border-radius: 3px;
    // Dynamic calculation of props    margin: ${props =&gt; };
    padding: ${props =&gt; }
`
render ( &lt;Input size='1em'&gt;&lt;/Input&gt;  &lt;Input size='2em'&gt;&lt;/Input&gt; )

Animation

Animation will generate a random class name without contaminating the global

import { keyframes } from 'styled-components'
// CSS animationconst rotate360 = keyframes`
    from {
        transform: rotate(0);
    }
    to {
        transform: rotate(360deg);
    }
`
const Rotate = `
    animation: ${rotate360} 2s linear infinite;
`
render ( &lt;Rotate&gt;  💅  &lt;/Rotate&gt; )

Conclusion

Although styled-components solves most problems and increases maintainability, it destroys the native experience. We often need to write more code to meet business requirements. We hope there will be a better solution in the future. For more information about the js library styled-components, please pay attention to my other related articles!