import './App.css';
const App = () => {
return(
<div className="App">
가장 기본적인 스타일링 방식
</div>
)
}
// App.css
.App {
text-align:center;
}
CSS 전처리기로 복잡한 작업을 쉽게 할 수 있게 해주고, 스타일 코드의 재활용성을 높여줄 뿐만 아니라 코드의 가독서응ㄹ 높여서 유지 보수를 더욱 쉽게 해줍니다
// sass 사용을 위해 라이브러리 설치 필요
npm install sass
// SassCompoent.sass
$primary-color : #333333;
// sass 는 중괄호와 세미콜론을 작성하지 않음
body
color: #primary-color
// SassCompoent.scss
$primary-color : #333333;
body {
color: #primary-color;
.container {
...
}
}
import './SassCompoent.scss'
const SassComponent () => {
return(
...
)
}
// styles/utils.scss
// 변수 사용
$red : #fa5252;
$orange : #fd7e14;
$yellow : #fcc419;
$green : #40c057;
$blue : #330af0;
$indigo: #5c7cfa;
$violet: #7950f2;
@mixin square($size) {
$calculated: 32px * $size;
width: $calculated;
height: $calculated;
}
// SassCompoent.scss
// scss 파일을 불러올때는 import구문을 사용
@import './styles/utils.scss';
// 외부 라이브러리로 설치한 파일을 불러올때는 물결표시를 사용
@import '~open-color/open-color'
$primary-color : #333333;
body {
color: #primary-color;
.container {
...
}
}
webpack.config.js 의 sass-loader 설정
프로젝트내에서 scss 파일읠 불러올때 상대경로가 아닌 절대경로를 사용하여 불러올수 있도록 설정 할 수 있습니다
npm run eject
혹은 yarn eject
를 실행하면 숨겨진 모든 설정을 밖으로 추출해주는 명령어라고 한다.
npm run eject
실행하고 나면 리액트 프로젝트 생성시 숨겨져 있던 webpack.config.js 등 빌드와 관련된 파일들을 꺼내어 커스터마이징 할 수 있다
다만, 실행하고 나면 두번다시 되돌릴 수 없기때문에 주의해서 사용해야한다
// webpack.config.js
{
test: sassRegex,
exclude: sassModuleRegex,
use: getStyleLoders({
importLoaders: 3,
sourceMap: isEnvProduction ? shouldUseSourceMap : isEnvDevelopment,
}).concat({
loader : require.resolve('sass-lader'),
options : {
sassOptions : {
includePaths : [paths.appSrc + '/styles']
},
additionalData: `@import 'utils'`
}
}),
sideEffects: true
}
CSS Module은 CSS를 불러와서 사용할때 클래스 이름의 고유한 값,
즉 [파일이름]_[클래스 이름]__[해시값]
형태로 자동으로 만들어서 스타일 클래스 이름이 중첩되는 현상을 방지해주는 기술입니다
// CSSModule.module.css
:global .somethig {
font-weight: 800;
color: aqua;
}
.wrapper {
background: black;
padding: 1rem;
color:white;
font-size: 2rem;
}
.inverted {
background: white;
color:black;
}
import styles from './CSSModule.module.css';
const CSSModule = () => {
return(
<div className={styles.wrapper}> // 출력예시 .CSSModule_wrapper__1SbdQ
안녕하세요 !
// 글로벌 스타일을 사용안 클래스는 일반 문자열로 적용
<span className="something">CSS Module!</span>
</div>
)
}
const CSSModule = () => {
return(
<div className={`${styles.wrapper} ${styles.inverted}`}>
...
</div>
)
}
const CSSModule = () => {
return(
<div className={[styles.wrapper,styles.inverted].join(' ')}>
...
</div>
)
}
npm install classnames
import classNames from 'classnames';
classNames('one' ,'two');
classNames('one' ,{ tow : true }); // 조건부
{ }
를 사용하여 조건이 만족할 때, 클래스를 추가 할 수 있습니다
const MyComponent - ({ highlighted, theme }) => (
<div className={classNames('MyComponent', { highlighted }, theme)}></div>
)
classnames에 내장되어있는 bind 함수를 사용하면 가독성이 높아집니다
const cx = classNames.bind(styles);
const CSSModule = () => {
return(
<div className={cx(wrapper, inverted)}>
...
</div>
)
}
자바스크립트 안에 스타일을 선언하는 방식으로 CSS-in-JS
라고 부릅니다
npm install styled-components
import styled , { css } from 'styled-components';
const Box = styled.div`
padding: 1rem;
background: ${ props => props.color || 'blue'}; // props에서 전달 된 값 참조
display:flex;
`
const Button = styled.button`
padding: 0.5rem;
font-size:1rem;
font-weight: 600;
background: white;
color:black;
text-align:center;
boder:2px solid black;
&:hover {
background: rgba(255,255,255, 0.9);
}
// props 에서 전달받은 조건부로 css 추가 가능
${ props => props.inverted && css`
background:black;
color:white;
&:hover {
background: white;
color:black;
}
`}
`
const StyledComponent = () => (
<Box color="gray">
<Button>버튼</Button>
<Button inverted={true}>반전 버튼</Button>
</Box>
)
import styled, { css } from 'styled-components'
const sizes = {
desktop : 1024,
tablet : 768
}
const media = Object.keys(sizes).reduce((acc, label) => {
acc[label] = (...args) => css`
@media (max-width: ${sizes[label] / 16} em) {
${css(...args)};
}
`
}, {})
const Box = styled.div`
padding:1rem;
background:gray;
${media.desktop`width: 768px;`}
${media.tablet`width: 100%;`}
`