Search code examples
javascriptreactjsstyled-components

How exactly does styled-components syntax work?


I was looking at styled-components and I saw this syntax:

const Title = styled.h1`
  font-size: 1.5em;
  text-align: center;
  color: palevioletred;
`;

I can't understand what is going on under the hood and what property is actually applied to the styled object. Is there anyone that can explain to me how this code even runs?


Solution

  • Read about tagged templates

    This is basically a function, but you can run it without ()

    const styled = data => {
      return data + ' JavaScript';
    };
    
    const data = styled `I love`;
    
    console.log(data);

    Examples with built-in functions:

    console.log('a b c'.split ` `)
    console.log(Object.entries `abc`)
    console.log([1, 2, 3].concat `abc`)