Code States
Front-end boost camp
Today
I
Learned
๐ 46์ผ์ฐจ ๋ฆฌ์กํธ ์ปค์คํ ์ปดํฌ๋ํธ~? + 47์ผ์ฐจ ๊ณผ์
# with npm
$ npm install --save styled-components@latest
# with yarn
$ yarn add styled-components
import styled from "styled-components"
-- Templete Literals ์ฌ์ฉ : ๋ฐ์ดํ๊ฐ ์๋ ๋ฐฑ ํฑ(`)์ฌ์ฉ
//Styled Components๋ก ์ปดํฌ๋ํธ๋ฅผ ๋ง๋ค๊ณ
const BlueButton = styled.button`
background-color: blue;
color: white;
`;
export default function App() {
// React ์ปดํฌ๋ํธ๋ฅผ ์ฌ์ฉํ๋ฏ์ด ์ฌ์ฉํ๋ฉด ๋ฉ๋๋ค.
return <BlueButton>Blue Button</BlueButton>;
}
-- ์ปดํฌ๋ํธ๋ฅผ ์ ์ธํ๊ณ styled()์ ์ฌํ์ฉํ ์ปดํฌ๋ํธ ์ ๋ฌ ํ ์ถ๊ฐํ๊ณ ์ถ์ ์คํ์ผ ์์ฑ ์์ฑ
const BlueButton = styled.button`
background-color: blue;
color: white;
`;
//๋ง๋ค์ด์ง ์ปดํฌ๋ํธ๋ฅผ ์ฌํ์ฉํด ์ปดํฌ๋ํธ๋ฅผ ๋ง๋ค ์ ์์ต๋๋ค.
const BigBlueButton = styled(BlueButton)`
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>
</>
);
}
-- ๋ฆฌํฐ๋ด ๋ฌธ๋ฒ ${} ์ ์ฌ์ฉํ์ฌ js์ฝ๋ ์ฌ์ฉ
-- props๋ฅผ ๋ฐ์์ค๋ ค๋ฉด props๋ฅผ ์ธ์๋ก ๋ฐ๋ ํจ์๋ฅผ ๋ง๋ค์ด ์ฌ์ฉ
//๋ฐ์์จ prop์ ๋ฐ๋ผ ์กฐ๊ฑด๋ถ ๋ ๋๋ง์ด ๊ฐ๋ฅํฉ๋๋ค.
const Button1 = styled.button`
background: ${(props) => (props.skyblue ? "skyblue" : "white")};
`;
export default function App() {
return (
<>
<GlobalStyle />
<Button1>Button1</Button1>
<Button1 skyblue>Button1</Button1>
</>
);
}
Props ๊ฐ์ผ๋ก ๋ ๋๋งํ๊ธฐ
-- props ๊ฐ์ ํต์งธ๋ก ํ์ฉํด ์ปดํฌ๋ํธ ๋ ๋๋ง์ ํ์ฉ
-- ๋๊ฐ์ด ์ผํญ ์ฐ์ฐ์๋ฅผ ์ฌ์ฉํ๊ณ ์์ง๋ง props.color๊ฐ ์๋ค๋ฉด white๋ฅผ, props.color๊ฐ ์๋ค๋ฉด Props.color์ ๊ฐ์ ๊ทธ๋๋ก ๊ฐ์ ธ์์ ์คํ์ผ ์์ฑ๊ฐ์ผ๋ก ๋ฆฌํด
์ผํญ์ฐ์ฐ์ ์๋์ด๋ ๊ฐ๋ฅ
//๋ฐ์์จ prop ๊ฐ์ ๊ทธ๋๋ก ์ด์ฉํด ๋ ๋๋งํ ์๋ ์์ต๋๋ค
const Button1 = styled.button`
background: ${(props) => (props.color ? props.color : "white")};
`;
//๋ค์๊ณผ ๊ฐ์ ํ์์ผ๋ก๋ ํ์ฉํ ์ ์์ต๋๋ค.
const Button2 = styled.button`
background: ${(props) => props.color || "white"};
`;
export default function App() {
return (
<>
<GlobalStyle />
<Button1>Button1</Button1>
<Button1 color="orange">Button1</Button1>
<Button1 color="tomato">Button1</Button1>
<br />
<Button2>Button2</Button2>
<Button2 color="pink">Button2</Button2>
<Button2 color="turquoise">Button2</Button2>
</>
);
}
import { createGlobalStyle } from "styled-components";
const GlobalStyle = createGlobalStyle`
button {
padding : 5px;
margin : 2px;
border-radius : 5px;
}
`
function App() {
return (
<>
<GlobalStyle />
<Button>์ ์ญ ์คํ์ผ ์ ์ฉํ๊ธฐ</Button>
</>
);
}
import styled from "styled-components";
const Practice = styled.button`
padding: 1rem;
font-size: 2rem;
background: pink;
transition: 0.5s;
&:hover {
background: purple;
color: white;
}
`;
export default function App() {
return <Practice>Practice!</Practice>
}
์ค๋ ํ์ด๋ถ๊ณผ์ ์์ ์ผ๋ก ์์ง ๊ฐ์ ์ก์ ์๊ฐ ์์๋ ๋ฆฌ์กํธ์ ๋ํด ํ~! ๊ฐ์ ์ก์๋ณผ ์ ์์๋ค. ํ์ด ํ๋ก๊ทธ๋๋ฐ์ ์์ง ๋ค ๊ตฌํํ์ง ๋ชปํด์ ์ค๋ ๋ณต์ตํ๊ณ css ๊ธฐ๋ฅ ๋ ๋ฃ์ด๋ณผ ์์ ~