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?
CodePudding user response:
This basically allows you to create Custom Tag in JSX. You can also pass props to the styling properties in styled-components.
If you have this jsx:
<Title>This is Custom H1</Title>
const Title = styled.h1`
color: red;
`
It will render HTML like this:
<h1 >This is Custom H1</h1>
where the class of h1 tag will have these properties:
.someRandomAlphabet{
color: red;
}
CodePudding user response:
You create styled h1 element, for example in Header component :
const Title = styled.h1`
font-size: 2rem;
text-align: center;
color: blue;
`;
You use it like a <h1>
tag but with custom name:
<Title>My portfolio</Title>
You finally get the static hash class name sc-<hashedStringName>
and one is dynamic class:
<h1 >My portfolio</h1>
So styled-components:
- generate static class name
- generate dynamic class name
CodePudding user response:
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`)