Vanilla CSS
CSS code is decoupled from JSX code
CSS code is not scoped to components -> CSS rules may clash across components
How to Scoping?
Inline Style
use inline style by jsx => { } react에서는 style 값을 표준 동적 값 문법으로 전달해야함 {{ key : value }}
일반적으로 cammel 방식 선호
return (<p style = {{
color : 'red',
textAlign : 'center',
backgroundColor : emailNotValid ? 'green' : 'blue'
}}
);
Inline Style의 장단점
Quick & easy to add to JSX
Sytles only affect the element to which you add them.
Dynamic(conditioning) Sytling is simple.
You need to style every element individually.
No separation between CSS & JSX code.
<label className = {`label ${emailNotValid ? 'invalid' : ''}`}>
Email </label>
<input
className = {emailNotValid ? 'invalid' : undefined}
/>
조건부 클래스 적용 : undefined 와 삼항 연산자를 통해 동적으로 class를 지정하고, 그에 따른 css style을 적용할 수 있다.
혹은 백틱 ` 을 사용하여 `${ } 을 통해 동적으로 className을 label과 invalid로 2개의 클래스를 가지도록 조절할 수 있다. (label class는 항상 기본으로 가짐)
"CSS Modules"
style이 원치 않는 모듈에 영향을 미치지 않도록 Scoping해주는 방법
파일내부의 className을 고유한것으로 보장해줌. (랜더링과정에서 빌드 툴에 의해 자동으로 고유한 값으로 생성)
import classes from './Header.module.css';
export default function Header() {
return (
<header>
<p className = {classes.paragraph}> ~~ </p>
</header>
);
}
CSS code is decoupled from JSX code
CSs classes are scoped to the component which imports them -> No CSS class name clashes
You may end up with many relatively small CSS files in your project
styled-components package
npm install styled-componetns
iimport {styled} from 'styled-components';
// JS object {styled}
const ControlContainer = styled.div`
display : flex;
flex-direction : column;
color : ${ ( {invalid } ) => invalid ? 'black' : 'red'};
// color : ${ (props) => props.invalid ? 'black' : 'red'};
`
const emailNotValid = true;
<ControlContainer $invalid = {emailNotValid}> ~ </ControlContainer>
html element를 원하는 스타일을 가지는 개별적인 컴포넌트로 만들어줌.
2개의 `` 백틱을 사용.
*Tagged templates라는 JS 정규 기능을 함께 사용. (템플릿의 문자열을 입력으로써 받게 해줌)
내부 스타일 문법은 기본 css와 동일. (카멜 표기법 사용 X)
styled-component에서만 사용하고자 하는 속성 앞에는 $를 붙여줌으로써 구별해줌.
styled-component 심화
const Box = styled.div`
background-color: lightblue;
& p {
color: blue; // Container 내부의 p 태그에 스타일 적용
}
&:hover {
background-color: green; // Button이 hover 상태일 때
}
@media (max-width: 768px) {
background-color: lightcoral;
}
`;
- @media: 미디어 쿼리를 사용해 화면 크기나 장치에 따라 스타일을 적용하여 반응형 디자인을 구현
- & 기호: styled-components에서 현재 컴포넌트의 내부 요소에 스타일을 적용
- &:hover: pseudo 선택자를 사용해 호버 상태에서 스타일을 쉽게 적용
pseudo 선택자와 컴포넌트 이름 사이에 띄어쓰기가 없도록 주의
=> 다른 파일로 옮긴 후 import Box from ~ 으로 사용 가능.
Quuick & easy to add
You continue "thinking in "React" -> configurable style functions
Styles are scoped to components -> No CSS rule clashes
No clear separation of React & CSS code
You end up with many relatively samll "wrapper" components
보통 한가지 접근법으로만 css를 사용하지만, 원한다면 css 모듈 같은 다른 스타일링 접근법과 섞어 사용할 수 있다.
일반적으로, 단일 솔루션을 사용하는것을 권장.
Tailwind CSS
react뿐만 아니라 다른 웹 프레임워크에서도 사용 가능
css를 알지 않아도 사용 가능 !!!
npm install -D tailwindcss postcss autoprefixer
npx tailwindcss init -p
Add the paths to all of your template files in your tailwind.config.js file.
/** @type {import('tailwindcss').Config} */
export default {
content: [
"./index.html",
"./src/**/*.{js,ts,jsx,tsx}",
],
theme: {
extend: {},
},
plugins: [],
}
Add the Tailwind directives to your CSS
@tailwind base;
@tailwind components;
@tailwind utilities;
Start using Tailwind in your project
export default function Input({ label, invalid, ...props }) {
let labelClasses = "block mb-2 text-xs font-bold tracking-wide uppercase";
if(invalid) {
labelClasses += 'text-stone-400';
}else {
labelClasses += 'text-stone-300';
}
return (
<p>
<label className={labelClasses}>{label}</label>
</p>
);
}
+ 이외에도 본인이 원하는데로 커스텀 가능.
You don't need to know (a lot about) CSS
Rapid development
No style clashes between components since you don't define any CSS rules
Highly configurable & extensible
Relatively long className values
Any style changes require eaditing JSX
You end up with many relatively small "wrapper" components OR lots of copy & pasting
Template literals (Template strings) - JavaScript | MDN
Template literals are literals delimited with backtick (`) characters, allowing for multi-line strings, string interpolation with embedded expressions, and special constructs called tagged templates.
developer.mozilla.org
Install Tailwind CSS with Vite - Tailwind CSS
Setting up Tailwind CSS in a Vite project.
tailwindcss.com