-
[React] 리액트 styled-componentsWEB/ReactJS 2023. 6. 26. 14:04
💡 styled-components는 React에서 스타일을 적용하기 위한 강력한 라이브러리입니다. 이를 사용하면 JavaScript 코드 내에서 CSS 스타일을 작성하고 컴포넌트에 적용할 수 있습니다.
install
npm i styled-components
styled-components install error
- styled-compoennts intsall 시에 아래와 같은 error를 마주한다면
npm ERR! Cannot read properties of null (reading 'edgesOut')
- 다음과 같이 해결
npm install styled-components@latest // or yarn 사용 yarn install styled-components
styled-components 기본 사용법
- styled.div``과 같은 방식으로 컴포넌트를 생성하고, 속성을 전달할 수 있습니다.
import styled from "styled-components"; function App(){ return ( <Box></Box> ); } const Boxone = styled.div` width: 100px; height: 100px; `;
Props
props 사용법
- 전달한 속성은 ${(props) => props.bgColor}와 같은 방식으로 스타일 내에서 참조할 수 있습니다.
import styled from "styled-components"; function App(){ return ( <Box bgColor="teal"/> <Box bgColor="red"/> ); } const Boxone = styled.div` background-color: ${(props) => props.bgColor}; width: 100px; height: 100px; `;
style 상속
- styled.div``과 같이 스타일이 적용된 기존 컴포넌트를 상속하여 새로운 컴포넌트를 생성할 수 있습니다.
const Box = styled.div` background-color: teal; width: 100px; height: 100px; `; const Circle = styled(Box)` border-radius: 5px; `;
HTML 태그 대체
- as 속성을 사용하여 컴포넌트를 다른 HTML 태그로 대체할 수 있습니다.
function App(){ return ( <Btn>Button Tag</Btn> <Btn as="a" href="/">A tag</Btn> ); } const Box = styled.div` color: white; background-color: blue; `;
속성 설정
- styled.input.attrs({ required: true, minLength: 10 })와 같이 attrs 메소드를 사용하여 속성을 설정할 수 있습니다.
const Input = styled.input.attrs({ required: true, minLength: 10 })` background-color: tomato; `
Animation
- keyframes를 사용하여 애니메이션을 정의하고, animation 속성을 통해 컴포넌트에 애니메이션을 적용할 수 있습니다.
import styled, {keyframes} from "styled-components"; const animation = keyframes` from { transform: rotate(0deg); } to { transform: rotate(360deg); } ` const Box = styled.div` height: 200px; width: 200px; background-color: tomato; animation: ${animation} 1s linear infinite; ${Emoji} { &:hover { font-size: 98px; } } ` const Emoji = styled.span` font-size: 36px; `
ThemeProvider
- ThemeProvider 컴포넌트를 사용하여 테마를 설정할 수 있습니다. 이를 통해 컴포넌트 내에서 테마에 따라 스타일을 다르게 적용할 수 있습니다.
index.js
import React from "react"; import ReactDOM from "react-dom/client"; import { ThemeProvider } from "styled-components"; import App from "./App"; const darkTheme = { textColor: "whitesmoke", backgroundColor: "#111", }; const lightTheme = { textColor: "#111", backgroundColor: "whitesmoke", }; const root = ReactDOM.createRoot(document.getElementById("root")); root.render( <React.StrictMode> <ThemeProvider theme={darkTheme}> <App /> </ThemeProvider> </React.StrictMode> );
App.js
import styled from "styled-components"; const Text = styled.span` color: ${(props) => props.theme.textColor}; `;
728x90'WEB > ReactJS' 카테고리의 다른 글
[React] React Router (0) 2023.06.28 [React] React와 Node 연결 (0) 2022.10.12 [React] 리액트 프로젝트 시작하기 (0) 2022.10.10