4. Styled-components
keyword
styled-componets
1. styled-componets
๋ํ์ ์ธ CSS-in-JS ๋ผ์ด๋ธ๋ฌ๋ฆฌ
CSS ์์ฑ์ ์ปดํฌ๋ํธ๋ก ์ฌ๊ณ ํ ์ ์๋ ์ฅ์
sc๋ผ๋ ์ ๋์ฌ๊ฐ ๋ถ์ ์ ๋ํฌํ class name์ ์์ฑํจ
React ์ปดํฌ๋ํธ์์ ์ ๋ฌ๋ฐ์ props๋ฅผ ํตํด ๋์ ์ผ๋ก ์คํ์ผ ๋ณ๊ฒฝ ๊ฐ๋ฅ
Tagged templates literals์ ์ฌ์ฉํด ํจ์ ํํ๋ก ์ฌ์ฉํ ์ ์๋ค.
์ฌ์ฉ๋ฒ
import React from "react";
import styled from "styled-components";
const StyledButton = styled.button`
padding: 6px 12px;
border-radius: 8px;
font-size: 1rem;
line-height: 1.5;
border: 1px solid lightgray;
color: gray;
background: white;
`;
function Button({ children }) {
return <StyledButton>{children}</StyledButton>;
}
Tagged templates์ ํจ์๋ก ํ์ฑํ ์ ์์ด ์๋์ ๊ฐ์ด ํจ์ ํํ์ ์ฌ์ฉ์ด ๊ฐ๋ฅํ๋ค.
const StyledButton = styled.button`
padding: 6px 12px;
border-radius: 8px;
font-size: 1rem;
line-height: 1.5;
border: 1px solid lightgray;
color: ${(props) => props.color || "gray"};
background: ${(props) => props.background || "white"};
`;
์ถ๊ฐ ํค์๋
Tagged templates literals ๋งํฌ
ํ ํ๋ฆฟ ๋ฆฌํฐ๋ด์ ๋ฐ์ ๋ ํํ๋ก ํ๊ทธ๋ฅผ ์ฌ์ฉํ๋ฉด ํ ํ๋ฆฟ ๋ฆฌํฐ๋ด์ ํจ์๋ก ์ฌ์ฉํ ์ ์๋ค. ํ๊ทธ ํจ์์ ์ฒซ ๋ฒ์งธ ํ๋ผ๋ฏธํฐ๋ ์ ์ ๋ฌธ์์ด์ ๋ฐฐ์ด์ ๋๋จธ์ง ํ๋ผ๋ฏธํฐ์ ๋์ ๋ฐ์ดํฐ์ธ ํํ์์ ์ ๋ฌ๋ฐ๋๋ค.
function myTag(strings, personExp, ageExp) {
var str0 = strings[0]; // "that "
var str1 = strings[1]; // " is a "
// ์ฌ์ค ์ด ์์ ์ string์์ ํํ์์ด ๋ ๊ฐ ์ฝ์
๋์์ผ๋ฏ๋ก
// ${age} ๋ค์๋ ''์ธ string์ด ์กด์ฌํ์ฌ
// ๊ธฐ์ ์ ์ผ๋ก strings ๋ฐฐ์ด์ ํฌ๊ธฐ๋ 3์ด ๋ฉ๋๋ค.
// var str2 = strings[2];
var ageStr;
if (ageExp > 99) {
ageStr = "centenarian";
} else {
ageStr = "youngster";
}
// ์ฌ์ง์ด ์ด ํจ์๋ด์์๋ template literal์ ๋ฐํํ ์ ์์ต๋๋ค.
return str0 + personExp + str1 + ageStr;
}
var output = myTag`that ${person} is a ${age}`;
console.log(output);
// that Mike is a youngster
with Babel
next.js๋ SSR(Server Side Rendering) ํ๋ ์์ํฌ๋ก ์๋ฒ์์ pre-redering๋ HTML ๋ฌธ์๋ฅผ ์ ๊ณตํ๋ค. ์ด๋ฅผ ํตํด ๊ฒ์ ์์ง์ด ์น ์ฌ์ดํธ๋ฅผ ๋ถ์ํ ์ ์๋๋ก ๊ฒ์ ์์ง ์ต์ ํ(SEO)๋ฅผ ์ ๊ณตํ๋ค.
์ด๊ธฐ ์๋ฒ ์ฌ์ด๋ ๋ ๋๋ง ํ ํด๋ผ์ด์ธํธ ์ฌ์ด๋ ๋ ๋๋ง์ด ๋ฐ์ํ ๋ styled-components์ class name์ ํด์๊ฐ์ด ์๋ฒ์ ํด๋ผ์ด์ธํธ ๊ฐ์ ๋ถ์ผ์นํ ์ ์์ด ์๋ฌ๊ฐ ๋ฐ์ํ๋ค. ์ด๋ babel-plugin-styled-components
๋ฅผ ์ฌ์ฉํด ์๋ฒ์ ํด๋ผ์ด์ธํธ ๊ฐ์ ์ผ๊ด๋ class name์ ์์ฑํด ๋ฌธ์ ๋ฅผ ํด๊ฒฐํ ์ ์๋ค.
๋ํ, ๋ณด๋ค ํธ๋ฆฌํ ๋๋ฒ๊น ์ ์ํด ์ปดํฌ๋ํธ ์ด๋ฆ์ class name์ ํด์ฌ๊ฐ ์ ๋์ฌ๋ก ์ถ๊ฐํ๋ค.
Last updated