[React Master Class By Nomad Coders] #2. Styled-Components

OFFDUTYBYBLO·2021년 12월 6일
0

React 

목록 보기
13/14
post-thumbnail

1. Styled-Components를 사용하는 이유

  • 각 Element(HTML Tag)들이 어떤 목적으로 사용되는지 한 눈에 파악할 수 있다.
  • Style을 위해 ClassName을 사용할 필요가 없다.
  • 비슷한 스타일이 적용될 예정이라면 extend 기능을 사용할 수 있다.( 재사용성 )
  • Styled-Components에서 지원하는 기능들을 사용하여 JSX 코드를 더 간결하게 사용할 수 있다.

2. as

  • style을 확장해서 사용하고 싶은데 사용하는 Element(HTML Tag)가 다를 경우 해당 Element를 교체해서 사용할 수 있다.
const Box = styled.div`
	display: flex;
	align-item: center;
`;

// --- jsx --- 
<Box as="a" />
// => 렌더링 후, 확인해보면 div가 아닌 a로 적용

3.attrs

  • Element에 속성을 지정할 수 있다.
const Input = styled.input.attrs({required:true})``;
  • 모둔 Input component에 required 속성이 적용된다.

4.animation

  • Styled-Components에서 animation을 사용하는 방법이다.
// 1.keyframes를 import
import { keyframes } from 'styled-components';

// 2. animation을 정의할 component 생성
const animationTest = keyframes`
	from {
	~~~~~
	~~~~~
	}
	to {
	~~~~
	~~~~
	}
`;

// 3. animation을 적용할 component에 animation 속성을 추가해준다.
const Box = styled.div`
	animation: ${animationTest} 1s linear infinite;
`;

5. theme

  • Styled-Component의 ThemeProvider를 사용해서 전역 스타일을 적용한다.
// 1. index.js에서 설정(최상위 js파일)
import React from 'react';
import ReactDOM from 'react-dom';
// 2. Import ThemeProvider
import { ThemeProvider } from 'styled-components';
import App from './App';

// 4. ThemeProvider는 theme prop이 필요하다. 
//    theme style을 지정해주는 object를 생성한다.
//    해당 object에서 원하는 스타일 데이터를 지정할 수 있다. 
const GrobalTheme = {
	textAlign: 'center',
	display: 'flex',
};

ReactDOM.render(
	<React.StrictMode>
  // 3. <App />을 <ThemeProvider>로 감싸준다.
		<ThemeProvider theme={GrobalTheme}>
			<App />
		</ThemeProvider>
	</React.StrictMode>,
	document.getElementById('root'),
);
profile
블로그 운영 x

0개의 댓글