[React] CSS-Style

bbung95·2023년 1월 26일
0

React

목록 보기
6/8
post-thumbnail

CSS

기존 HTML에서의 style은 .css로 작성하였습니다.
html

<link rel="stylesheet" src="./style.css">

<button class="btn">버튼</button>

css

.btn{
	width : 100px;
    height : 60px;
    font-size : 20px;
    color : #fff;
}

하지만 React는 html DOM을 JS를 통해 렌더링하는 라이브러리로 기존의 방식과는 다른 방식을 사용하게됩니다.

Inline

HTML은 구분자로 세미콜론( ; )을 사용하며 문자열을 전달했습니다.
html

<div style="color : red; font-size : 16px;">Inline</div>

리엑트는 JSX 문법을 사용하며 문자열이 아닌 객체의 형태로 전달합니다.

component

<div style={{color : "red", fontSize : "16px"}}>Inline</div>
  • JSX 문법을 사용기에 CamelCase를 기본으로 사용합니다.
  • 사이즈를 설정하는 숫자 뒤에 단위를 작성하지 않을시 자동으로 px가 붙습니다.
  • Inline 방식은 되도록 권장하지 않습니다.

CSS module

React에서 지원하는 CSS style 방법으로 className이 중복되는 문제점을 해결할 수 있습니다.

  • 작성한 스타일을 객체로 불러와 className에 부여할 수 있습니다.
  • 재사용이 가능한 CSS를 작성할 수 있습니다.
  • 기존 css 작성방식과 동일하게 작성할 수 있습니다.
  • [name].module.css 네이밍 컨벤션을 지킵니다.

button.module.css

.btn {
    width: 100px;
    height: 60px;
    color: #000;
    font-size: 20px;
}

component

import styled from "./button.module.css";

const Button = () => {
  return (
	<button className={styled.btn}></button>
  )
}

export defualt Button;

style이 같으면 같은 className을 부여받으며 틀릴경우 중복의 방지로 다른 className을 부여받습니다.
각각 style은 header에 소스코드로 작성됩니다.

CSS-in-JS

CSS를 JS로 통합하는데 도움이 되는 라이브러리입니다

외부의 파일에 CSS를 정의하는 대신에 JS와 결합하는 패턴을 의미합니다.

  • 리엑트 기본 자원이 아닌 라이브러리로 지원합니다.
  • 대표적으로 Styled-Component가 있습니다.

Styled-Component

각각 컴포넌트에 맞도록 컴포넌트가 렌더링 될 경우에만 스타일 컴포넌트를 렌더링합니다.

라이브러리로 추가로 설치가 필요합니다.

npm install styled-components

styled-components.js

import styled from "styled-components";

export const Btn = styled.button`
    width: 100px;
    height: 60px;
    color: #000;
    font-size: 20px;
`;

component

import * as S from "./styled-components";

<S.Btn>+</S.Btn>

props

props와 같이 값을 받아 올 수 있으며 조건문을 통한 분기처리가 가능합니다.

import * as S from "./styled-components";

const stocked = true;

<S.Btn stocked={stocked}>+</S.Btn>
 
// styled-component
export const Btn = styled.button`
	width: 100px;
    height: 60px;
    color: ${(props) => (props.stocked ? props.stocked : "red")};
    font-size: 20px;
`;

0개의 댓글