💅🏻styled-components
- 기존 DOM을 만드는 방식인 css,scss 파일을 밖에 두고 쓰지 않음 => CSS in JS 방식임
- css가 전역으로 중첩되지 않으며 class명 중복을 줄일 수 있음
- 패키지 설치
yarn add styled-components
- 적용하고자 하는 컴포넌트 상단에 import
import styled from 'styled-components'
💡 사용 방법 예제
01. 기본 예제
const Father = styled.div`
display:flex;
width:100px;
height:100px;
`;
const Ex01 = () => {
return (
<Father>
Hello World!
</Father>
);
};
- 스타일링 할 태그 이름을 작명하여 변수로 지정한다.
styled.사용 할 태그
뒤에 백틱(``) 추가 후 백틱 안에서 css 스타일링
02. 응용 예제 ⭐️
02-1 props로 개별 스타일 속성 적용하기
const Father = styled.div`
display:flex;
width:100px;
height:100px;
`;
const Text = styled.h1`
color:${(props) => props.textColor}; //전달받은 컬러 적용
`;
const Ex02 = () => {
return (
<Father>
<Text textColor='red'>
Hello World!
</Text>
<Text textColor='blue'>
Bye World!
</Text>
</Father>
);
};
- 스타일 컴포넌트에 props를 주고 지정 스타일 컴포넌트에 props를 전달
- 삼항연산자로 조건에 따라 지정 가능
스타일속성 : ${props => props.프롭스명 ? 참일때속성 : 거짓일때 속성}
02-2 파라미터로 상속받아 적용하기 : 컴포넌트 extends
const Box = styled.div`
background-color: ${(props) => props.bgColor};
width: 100px;
height: 100px;
`;
const Circle =styled(Box)`
border-radius:50px;
`;
const Ex03 = () => {
return (
<Box bgColor='gray'>
</Box>
<Circle bgColor='tomato' />
);
};
const 스타일컴포넌트이름 = styled.(상속받을 스타일컴포넌트명)'수정 or 추가할 스타일 코드 '
( 따옴표는 백틱입니다)
02-3 as
props 를 사용하여 html태그를 변경하기
const Father = styled.div`
display: flex;
`;
const Btn = styled.button`
color: white;
background-color: tomato;
border: 0;
border-radius: 15px;
`;
const Ex03 = () => {
return (
<Father as='header'> {}
<Btn> Login </Btn>
<Btn as='a' href='/'> {}
Login
</Btn>
</Father>
);
};
- 스타일지정컴포넌트에 지정된 태그로만 따르지 않아도 된다
- 스타일 컴포넌트에 as를 사용하여 사용될 태그를 변경할 수 있다.
02-4 컴포넌트에 속성 공통 적용하기 : attrs
const Father = styled.div`
display: flex;
`;
const Input = styled.input.attrs({ required: true, minLength: '10' })`
background-color: tomato;
`;
const Ex03 = () => {
return (
<>
<Father>
<Input />
<Input />
<Input />
<Input />
<Input />
<Input />
</Father>
</>
);
};
export default Ex03;
.attrs({속성명:속성값})
- 같은 속성을 갖는 스타일컴포넌트를 다수 사용할 경우 사용한다
02-5 애니메이션 추가하기 : keyframes
- 사용할 컴포넌트 상단에 import 하기
import { keyframes } from 'styled-components';
const 스타일컴포넌트명 = keframes'애니메이션 코드'
(따옴표는 백틱입니다)
- 사용하기
animation : ${keyframes가 사용된 스타일컴포넌트명}
import styled, { keyframes } from 'styled-components';
const Wrapper = styled.div`
display: flex;
`;
const rotationAnimation = keyframes`
0% {
transform : rotate(0deg);
border-radius :0px;
}
50% {
transform : rotate(360deg);
border-radius : 100px;
}
100% {
transform : rotate(0deg);
border-radius :0px;
}
`;
const Box = styled.div`
height: 200px;
width: 200px;
background-color: tomato;
animation:${rotationAnimation} 1.5s linear infinite;
display:flex;
justify-content: center;
align-items: center;
span {
font-size :100px;
&:hover {
font-size:50px;
/* span:hover 와 같음 */
}
&:active {
opacity :0;
}
}
`;
const Ex04 = () => {
return (
<>
<Wrapper>
<Box>
<span>☺️</span>
</Box>
</Wrapper>
</>
);
};
export default Ex04;
02-6 스타일컴포넌트안에서 ${또다른 스타일컴포넌트} 중첩 사용하기
const Wrapper = styled.div`
display: flex;
`;
const Emoji =styled.span`
font-size:100px;
`;
const Box = styled.div`
height: 200px;
width: 200px;
background-color: tomato;
animation:${rotationAnimation} 1.5s linear infinite;
display:flex;
justify-content: center;
align-items: center;
${Emoji} {
&:hover {
font-size:10px;
}
}
`;
const Ex05 = () => {
return (
<>
<Wrapper>
<Box>
{}
<Emoji as='p'>☺️</Emoji>
</Box>
{}
<Emoji as='p'>👨🏻💻</Emoji>
</Wrapper>
</>
);
};
export default Ex05;
02-7 전역 지정하기
- index.js 파일에서 지정해서
- 각 컴포넌트 파일에서 스타일컴포넌트 내에서 props로 받기
- index.js 상단에
ThemeProvider
import 하기
import {ThemeProvider} from'styled-components';
<App/>
을 <ThemeProvider theme={적용할스타일컴포넌트명}>
감싼다.
import React from 'react';
import ReactDOM from 'react-dom/client';
import App from './App';
import reportWebVitals from './reportWebVitals';
import { BrowserRouter } from 'react-router-dom';
import {ThemeProvider} from'styled-components';
const darkTheme ={
textColor:'whitesmoke',
backgroundColor:'#111',
};
const lightTheme ={
textColor:'#111',
backgroundColor:'#whitesmoke',
};
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
<React.StrictMode>
<BrowserRouter>
<ThemeProvider theme={darkTheme}>
<App />
</ThemeProvider>
</BrowserRouter>
</React.StrictMode>
);
reportWebVitals();
- 다크/화이트 모드를 가지고 싶다면, 각 property 들의 이름이 똑같아야함!⭐️
ex.다크모드에서 textColor:'whitesmoke'/ 화이트모드에서 textColor:'#111'
- 이것을 props로 전달받는 컴포넌트들은 적용한 property의 이름만을 사용함