-
[React] custom component/ Styled-ComponentcodeStates front-end/React 2023. 2. 20. 16:43반응형
목차
📌 custom component
📍 Component-Driven Development(CDD)
부품 단위로 UI 컴포넌트를 만들어나가는 개발
🔗 실제로 CDD 방법을 활용하여 UI를 구축하는 사이트
- 링크1 : BBC
- 링크2 : UN
Storybook
uikit.wfp.org
📍 구조적인 CSS
프로젝트 규모나 복잡도, 다양한 디바이스들의 등장으로 일괄된 CSS패턴이 없다는 것이 문제점으로 떠올라
이를 해결하기 위해 CSS 전처리기(CSS Preprocessor)라는 개념이 등장
이는 CSS가 구조적으로 작성될 수 있게 도움을 주는 도구이다
🔗 SASS(Syntactically Awesome Style Sheets)
CSS를 확장해 주는 스크립팅 언어
특정 속성의 값을 변수로 선언하여 필요한 곳에 선언된 변수를 적용하기도 하고,
반복되는 코드를 한 번의 선언으로 여러 곳에서 재 사용할 수 있도록 해 주는 등의 기능을 가진다.
SASS는 SCSS 코드를 읽어서 전처리한 다음 커파일해서 전역 CSS 번들 파일을 만들어주는 전처리기의 역할
//SASS 변수 사용 예제 $base-color: rgba(198, 83, 140, 0.88) .alert{ border : 1px solid $border-dark } .button{ color : $border-dark }
🔗 SASS의 문제점
단순히 계층 구조를 만들어 내는 것에 의지 -> CSS의 용량 상승
이를 해결하기 위해 BEM의 등장 -> 클래스명 선택자가 장황, 마크업의 불필요
컴포넌트 단위 개발로 진화 -> 캡슐화의 중요성 -> CSS-in-JS 탄생
대표적으로 Styled-Component
🔗 Styled-Component
Styled-Component 설치하기
# with npm $ npm install --save styled-components # with yarn $ yarn add styled-components
pakage.json(권장)
{ "resolutions": { "styled-components": "^5" } }
index.css
import styled from "styled-components"
🔗 Styled Components 문법
1. 컴포넌트 만들기
Templete Literals 문법 -> 따옴표가 아닌 백틱 사용
import styled from "styled-components"; //Styled Components로 컴포넌트를 만들고 const BlueButton = styled.button` background-color: blue; color: white; `; export default function App() { // React 컴포넌트를 사용하듯이 사용하면 됩니다. return <BlueButton>Blue Button</BlueButton>; }
2. 컴포넌트를 재활용해서 새로운 컴포넌트 만들기
import styled from "styled-components"; 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> </> ); }
3. props 활용하기
React 컴포넌트처럼 props를 내려줄 수 있다
💡 props로 조건부 렌더링
삼항연산자를 활용해 <Button> 컴포넌트에 skyblue라는 props가 있는지 확인
배경색이 있으면 skyblue , 없으면 white
import styled from "styled-components"; import GlobalStyle from "./GlobalStyle"; //받아온 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 값으로 렌더링
삼항연산자가 아니여도 가능하다
import styled from "styled-components"; import GlobalStyle from "./GlobalStyle"; //받아온 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> </> ); }
4. 전역 스타일 설정하기
// 전역에 스타일을 설정하고 싶을 때 import { createGlobalStyle } from "styled-components"; // 스타일 작성 const GlobalStyle = createGlobalStyle` button { padding : 5px; margin : 2px; border-radius : 5px; } ` // <GlobalStyle> 컴포넌트를 최상위 컴포넌트에서 사용해주면 전역 컴포넌트의 스타일이 적용 function App() { return ( <> <GlobalStyle /> <Button>전역 스타일 적용하기</Button> </> ); }
실습) CSS -> Styled-Component
주어진 css를 Styled-Component 로 바꾸기
* { margin: 0.5rem; } #practice { padding: 1rem; font-size: 2rem; background: powderblue; border-radius: 1rem; transition: 0.5s; } #practice:hover { background: cornflowerblue; color: white; transition: 0.5s; }
👉🏼 👉🏼 👉🏼
import styled from "styled-components"; // practice를 Button1로 바꿨다 const Button1 = styled.button` padding: 1rem; font-size: 2rem; background: ${(props) => (props.white ? "powderblue" : "cornflowerblue")}; border-radius: 1rem; transition: 0.5s; `; export default function App() { return ( <> <Button1 white>Practice!</Button1> <Button1>Practice!</Button1> </> ); }
반응형'codeStates front-end > React' 카테고리의 다른 글
[React] Redux (0) 2023.02.24 [React] Storybook, useRef (0) 2023.02.20 [React] UX 디자인 (0) 2023.02.15 [React] UI 디자인 (0) 2023.02.15 [React] UI/UX (0) 2023.02.15