styled-components는 React 애플리케이션에서 CSS 스타일을 작성하는 데 사용되는 라이브러리.
간단하게 사용법 정리해보자!
1. inline
import styled from 'styled-components';
const StyledParagraph = styled.p`
color: blue;
font-size: 16px;
`;
const App = () => {
return (
<div>
<StyledParagraph>이 텍스트는 파란색으로 스타일링됩니다.</StyledParagraph>
</div>
);
};
export default App;
2. Props 로 스타일 적용하기
props를 활용해서 동적으로 스타일 변경 가능
import styled from 'styled-components';
const StyledButton = styled.button`
background-color: ${props => (props.primary ? 'blue' : 'gray')};
color: white;
padding: 10px 20px;
border: none;
border-radius: 4px;
cursor: pointer;
`;
const App = () => {
return (
<div>
<StyledButton>기본 버튼</StyledButton>
<StyledButton primary>주요 버튼</StyledButton>
</div>
);
};
export default App;
3. 기존 스타일코드 props로 확장
import styled, { css } from 'styled-components';
const buttonStyles = css`
padding: 10px 20px;
border: none;
border-radius: 4px;
cursor: pointer;
`;
const primaryButtonStyles = css`
background-color: blue;
color: white;
`;
const secondaryButtonStyles = css`
background-color: gray;
color: white;
`;
const StyledButton = styled.button`
${buttonStyles}
${props => (props.primary ? primaryButtonStyles : secondaryButtonStyles)}
`;
const App = () => {
return (
<div>
<StyledButton>기본 버튼</StyledButton>
<StyledButton primary>주요 버튼</StyledButton>
</div>
);
};
export default App;
이렇게도 가능
import styled from 'styled-components';
// 기본 버튼 컴포넌트 정의
const Button = styled.button`
padding: 10px 20px;
background-color: blue;
color: white;
border: none;
border-radius: 4px;
font-size: 16px;
cursor: pointer;
`;
// 링크 역할을 하는 스타일링된 컴포넌트
const StyledLink = styled(Button).attrs({
as: 'a', // 해당 컴포넌트가 렌더링될 때 <a> 태그로 변환됨
href: 'https://www.example.com', // 링크 주소
target: '_blank', // 새 탭에서 열도록 설정
rel: 'noopener noreferrer', // 보안을 위한 권장 설정
})``; // 추가 스타일이 필요 없으므로 비워둠
const App = () => {
return (
<div>
<Button>기본 버튼</Button>
<StyledLink>이 버튼은 링크 역할을 합니다.</StyledLink>
</div>
);
};
export default App;
4. 태그 바꿔서 적용하기
import styled from 'styled-components';
// 기본 버튼 컴포넌트 정의
const Button = styled.button`
padding: 10px 20px;
background-color: blue;
color: white;
border: none;
border-radius: 4px;
font-size: 16px;
cursor: pointer;
`;
// 링크 역할을 하는 스타일링된 컴포넌트
const StyledLink = styled(Button).attrs({
as: 'a', // 해당 컴포넌트가 렌더링될 때 <a> 태그로 변환됨
href: 'https://www.example.com', // 링크 주소
target: '_blank', // 새 탭에서 열도록 설정
rel: 'noopener noreferrer', // 보안을 위한 권장 설정
})``; // 추가 스타일이 필요 없으므로 비워둠
const App = () => {
return (
<div>
<Button>기본 버튼</Button>
<StyledLink>이 버튼은 링크</StyledLink>
</div>
);
};
export default App;
- Button 컴포넌트를 정의하고 해당 컴포넌트를 확장해서 링크를 가지고 있는 StyledLink 컴포넌트 만들기
- StyledLink 컴포넌트는 attrs, as 'a' → <a> 태그로 변환되며 관련 속성이 추가로 설정되어 링크로서 동작하게 된다.
- 기존의 스타일을 재사용하면서 태그를 바꿔 원하는 컴포넌트로 변형 가능.
5. 상위 선택자, 중첩
&를 사용 상위 선택자에 스타일을 적용하거나 중첩된 스타일 만들기
import styled from 'styled-components';
const StyledContainer = styled.div`
background-color: lightgray;
&:hover {
background-color: darkgray;
}
& h1 {
color: blue;
}
`;
const App = () => {
return (
<div>
<StyledContainer>
<h1>이 텍스트는 파란색으로 스타일링됩니다.</h1>
</StyledContainer>
</div>
);
};
export default App;
6. 태그 속성 (attribute)
import styled from 'styled-components';
const StyledInput = styled.input.attrs({
type: 'text',
placeholder: '이름을 입력하세요',
})`
padding: 10px;
border: 1px solid gray;
border-radius: 4px;
`;
const App = () => {
return (
<div>
<StyledInput />
</div>
);
};
export default App;
attrs 메서드?
styled-components에서 제공하는 메서드 중 하나. 속성(attributes)을 추가하거나 수정할 수 있도록 해줌. 스타일링된 컴포넌트의 속성을 동적으로 설정하거나 변경 가능하게 함. 위의 예제에서는 attrs 메서드를 사용해서 Input컴포넌트에 type 속성을 text로, placeholder 속성을 '이름을 입력하세요.'로 설정. 이렇게 하면 Input 컴포넌트가 렌더링될 때 해당 속성이 적용되면서 초기상태 지정이 가능. attrs를 자꾸 사용하면서 스타일링된 컴포넌트의 재사용률을 더 높여보자!
7. 애니메이션
keyframe 임포트, 애니매이션 설정 가능
import styled, { keyframes } from 'styled-components';
const fadeInAnimation = keyframes`
from {
opacity: 0;
}
to {
opacity: 1;
}
`;
const StyledDiv = styled.div`
width: 200px;
height: 200px;
background-color: blue;
animation: ${fadeInAnimation} 2s ease-in-out;
`;
const App = () => {
return (
<div>
<StyledDiv />
</div>
);
};
export default App;
import styled, { keyframes } from 'styled-components';
// keyframes를 사용하여 애니메이션 정의
const fadeInAnimation = keyframes`
from {
opacity: 0;
}
to {
opacity: 1;
}
`;
// 애니메이션을 적용할 컴포넌트 정의
const AnimatedButton = styled.button`
padding: 10px 20px;
background-color: blue;
color: white;
border: none;
border-radius: 4px;
font-size: 16px;
cursor: pointer;
animation: ${fadeInAnimation} 1s ease-in-out;
&:hover {
background-color: darkblue;
}
`;
const App = () => {
return (
<div>
<AnimatedButton>애니메이션 버튼</AnimatedButton>
</div>
);
};
export default App;
8.Theme Provider
전역적으로 데이터 테마 적용하기
import styled, { ThemeProvider } from 'styled-components';
const Button = styled.button`
background-color: ${props => props.theme.primaryColor};
color: white;
padding: 10px 20px;
border: none;
border-radius: 4px;
cursor: pointer;
`;
const theme = {
primaryColor: 'blue',
};
const App = () => {
return (
<ThemeProvider theme={theme}>
<div>
<Button>기본 버튼</Button>
</div>
</ThemeProvider>
);
};
export default App;
Theme Provider 사용해서 다크모드 라이트모드 구현!
import React, { useState } from 'react';
import styled, { ThemeProvider } from 'styled-components';
// 다크 모드와 라이트 모드에 해당하는 테마 정의
const darkTheme = {
colors: {
primary: 'gray',
secondary: 'black',
text: 'white',
background: 'darkgray',
},
fontSize: '16px',
};
const lightTheme = {
colors: {
primary: 'blue',
secondary: 'gray',
text: 'black',
background: 'lightgray',
},
fontSize: '16px',
};
// 테마를 적용할 컴포넌트 정의
const StyledContainer = styled.div`
background-color: ${props => props.theme.colors.background};
padding: 20px;
`;
const StyledButton = styled.button`
background-color: ${props => props.theme.colors.primary};
color: ${props => props.theme.colors.text};
font-size: ${props => props.theme.fontSize};
padding: 10px 20px;
border: none;
border-radius: 4px;
cursor: pointer;
`;
const App = () => {
const [isDarkMode, setIsDarkMode] = useState(false);
const toggleTheme = () => {
setIsDarkMode(prevMode => !prevMode);
};
return (
<ThemeProvider theme={isDarkMode ? darkTheme : lightTheme}>
<StyledContainer>
<StyledButton onClick={toggleTheme}>
{isDarkMode ? '라이트 모드로 전환' : '다크 모드로 전환'}
</StyledButton>
</StyledContainer>
</ThemeProvider>
);
};
export default App;
- darkTheme, lightTheme 스타일 테마를 우선 정의해준다.
- useState 사용해서 isDarkMode라는 상태를 관리해주고
- toggleTheme 함수를 만들어서 버튼을 클릭할 때마다 상태가 바뀌도록 해준다.
- ThemeProvider 같이 임포트해주고 적용!
https://styled-components.com/docs
styled-components: Documentation
Learn how to use styled-components and to style your apps without stress
styled-components.com
'What I Learnd > TIL' 카테고리의 다른 글
TIL - localStorage 메소드 정리 (0) | 2023.08.03 |
---|---|
TIL - TypeScript로 회원가입, 로그인 기능 구현하기 (1) | 2023.08.02 |
TIL - TypeScript에서 Styled Components 라이브러리 사용하기 step by step (0) | 2023.07.30 |
TIL - 새로고침을 막아주는 .preventDefault 메서드 → TS에서는? (0) | 2023.07.28 |
TIL - React 전용 TypeScript 셋업 step by step / TypeScript에서 모듈 설치하기 (0) | 2023.07.28 |