๐ CSS in JS ๋ผ์ด๋ธ๋ฌ๋ฆฌ๋?
CSS in JS ๋ผ์ด๋ธ๋ฌ๋ฆฌ๋ฅผ ์ฌ์ฉํ๋ฉด CSS๋ ์ฝ๊ฒ Javascript ์์ ๋ฃ์ด์ค ์ ์์ผ๋ฏ๋ก, HTML + JS + CSS๊น์ง ๋ฌถ์ด์ ํ๋์ JSํ์ผ ์์์ ์ปดํฌ๋ํธ ๋จ์๋ก ๊ฐ๋ฐํ ์ ์๋ค. ํ์ฌ CSS in JS ๋ผ์ด๋ธ๋ฌ๋ฆฌ ์ค ๊ฐ์ฅ ์ธ๊ธฐ ์๋ ๋ผ์ด๋ธ๋ฌ๋ฆฌ๋ Styled Components ์ด๋ค.
๐ Styled Components ์ค์นํ๊ธฐ
// 1. ํฐ๋ฏธ๋์ ์๋์ ๋ช
๋ น์ด ํ ์ค์ ์
๋ ฅํ๋ค.
# with npm
$ npm install --save styled-components
# with yarn
$ yarn add styled-components
// 2. package.json์ ๋ค์ ์ฝ๋๋ฅผ ์ถ๊ฐ(๊ถ์ฅํ๋ ํธ)
// ์๋์ ์ฝ๋๋ฅผ ์ถ๊ฐํ๋ฉด ์ฌ๋ฌ ๋ฒ์ ์ Styled Components๊ฐ ์ค์น๋์ด ๋ฐ์ํ๋ ๋ฌธ์ ๋ฅผ ์ค์ฌ์ค๋ค.
{
"resolutions": {
"styled-components": "^5"
}
}
// 3. Styled Components๋ฅผ ์ฌ์ฉํ ํ์ผ๋ก ๋ถ๋ฌ์จ๋ค.
import styled from "styled-components"
๐ Styled Components ๋ฌธ๋ฒ
1. ์ปดํฌ๋ํธ ๋ง๋ค๊ธฐ
- Styled Components๋ ES6์ Templete Literals ๋ฌธ๋ฒ์ ์ฌ์ฉํ๋ค.
- ์ฆ, ๋ฐ์ดํ๊ฐ ์๋ ๋ฐฑํฑ(`)์ ์ฌ์ฉํ๋ค.
- ์ปดํฌ๋ํธ๋ฅผ ์ ์ธํ ํ styled.ํ๊ทธ์ข ๋ฅ๋ฅผ ํ ๋นํ๋ค.
- ๋ฐฑํฑ ์์ ๊ธฐ์กด์ CSS๋ฅผ ์์ฑํ๋ ๋ฌธ๋ฒ๊ณผ ๋๊ฐ์ด ์คํ์ผ ์์ฑ์ ์์ฑํ๋ค.
- React ์ปดํฌ๋ํธ๋ฅผ ์ฌ์ฉํ๋ฏ ๋ฆฌํด๋ฌธ ์์ ์์ฑํด์ฃผ๋ฉด ์คํ์ผ์ด ์ ์ฉ๋ ์ปดํฌ๋ํธ๊ฐ ๋ ๋๋๋ ๊ฒ์ ํ์ธํ ์ ์๋ค.
const ์ปดํฌ๋ํธ ์ด๋ฆ = styled.ํ๊ทธ์ข
๋ฅ`
css ์์ฑ1: ์์ฑ๊ฐ;
css ์์ฑ2: ์์ฑ๊ฐ;
`;
const BlueButton = styled.button` //<-๋ฐฑํฑ(1)
background-color: blue;
color: white;
`; //<-๋ฐฑํฑ(2)
import styled from "styled-component";
// 1. Styled Component๋ก ์ปดํฌ๋ํธ ๋ง๋ ๋ค.
// ์ปดํฌ๋ํธ๋ฅผ ์ ์ธ(const BlueButton)ํ ํ styled.ํ๊ทธ์ข
๋ฅ(styled.button)๋ฅผ ํ ๋น
const BlueButton = styled.button` //<-๋ฐฑํฑ(1)
background-color: blue;
color: white;
`; //<-๋ฐฑํฑ(2) ์ฌ๊ธฐ ๋ฐฑํฑ์ ์ ์๋ณด์ด๋ ๋ ํฌ๊ฒ ๋ ์ผํจ ๐
export default function App() {
return <BlueButton> Blue Button </BlueButton>;
}
2. ๊ธฐ์กด ์ปดํฌ๋ํธ๋ฅผ ์ฌ์ฌ์ฉํด์ ์๋ก์ด ์ปดํฌ๋ํธ ๋ง๋ค๊ธฐ
์ปดํฌ๋ํธ๋ฅผ ์ ์ธํ๊ณ styled() ์ ์ฌํ์ฉํ ์ปดํฌ๋ํธ๋ฅผ ์ ๋ฌํด์ค ๋ค์, ์ถ๊ฐํ๊ณ ์ถ์ ์คํ์ผ ์์ฑ์ ์์ฑํ๋ค.
const ์ปดํฌ๋ํธ ์ด๋ฆ = styled(์ฌ์ฌ์ฉ ํ ์ปดํฌ๋ํธ)`
์ถ๊ฐํ css ์์ฑ1: ์์ฑ๊ฐ;
์ถ๊ฐํ css ์์ฑ2: ์์ฑ๊ฐ;
`;
cosnt BigBlueButton = styled(BlueButton)`
padding: 10px;
margin-top: 10px;
`;
import style from "styled-components";
const BlueButton = styled.button`
background-color: blue;
color: white;
`;
//๋ง๋ค์ด์ง BlueButton ์ปดํฌ๋ํธ๋ฅผ ์ฌ์ฌ์ฉํด์ ์ ์ปดํฌ๋ํธ ๋ง๋ค๊ธฐ
const BigBlueButton = styled(BlueButon)`
padding: 10px;
margin-top: 10px;
`;
//์ฌ์ฌ์ฉํ ์ปดํฌํดํธ๋ ๋ ์ฌ์ฌ์ฉํ ์ ์๋ค.
const BigRedButton = styled(BigBlueButton)`
background-color: red;
`
export default function App(){
return (
<>
<BlueButton>Blue Button</BlueButton>
<br />
<BigBlueButton>Big Blue Button</BigBlueButton>
<br />
<BigRedButton>Big Red Button</BigRedButton>
</>
);
}
)
'React' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
Cmarket (Hooks ๋ฒ์ )/ useEffect (0) | 2022.07.06 |
---|---|
[React] CDD ๊ฐ๋ฐ ๋๊ตฌ Styled Components Props ํ์ฉ (0) | 2022.07.01 |
[React] ์ปดํฌ๋ํธ ์ฃผ๋ ๊ฐ๋ฐ Component Driven Development (CDD) (0) | 2022.06.30 |
React event.target.value (0) | 2022.06.30 |
React State Practice (0) | 2022.06.30 |