2024년 7월 29일 월요일

css in js

css in js

CSS IN JS

말그대로, javascript 를 이용해서 css를 정의하는 한다는 것이다.
이런저런 라이브러리가 있지만 실무에서는 emotion+styled 라이브러리를 주로 사용한다.

css를 javascript로 정의해서 사용하면 머가 장점일까?

  1. className 을 변수로 하면 컴파일(빌드)할때 변수값에 해당하는 스타일 값을 중복안되도록 고유의 클래스 이름으로 생성한다.
  2. 스타일을 변수로 지정하면 에디터 등에서 쉽게 찾아볼수 있다.
  3. 사용하지 않는 코드에는 eslint 등에서 에러로 표시되기 때문에 미사용 스타이일은 삭제하기 쉽다.
  4. 단위테스트 작성이 쉽다.

불편한점은?
생성된 스타일로는 디버깅이 불편하다.

아래의 기사에서 css in js 라이브러리에 대해서 비교한것을 볼수있다.
https://techblog.zozo.com/entry/zozotown-css-in-js

2024년 현재 권장하는 선택지는 @emotion/styled이다.

emotion 라이브러리

Emotion 은 JS 로 css 스타일을 작성하도록 제작된 라이브러리다.
@emotion/css 를 설치( npm i @emotion/css )하면 아래와 같이 변수값을 css 기술할때 사용할수 있다.
프레임워크에 의존하지 않으므로 일반 자바스크립트 프레임워크에서도 어떤 자바스크립트 프레임워크에서도 사용가능하다.

import { css } from '@emotion/css'

const color = 'white'

render(
 <div
   className={css`
     padding: 32px;
     background-color: hotpink;
     font-size: 24px;
     border-radius: 4px;
     &:hover {
       color: ${color};
     }
   `}
 >
   Hover to change color.
 </div>

@emotion/react , @emotion/styled

emotion을 reactjs 에서 사용할때 사용성을 좋게 하기 위한 몇가지 기능을 추가한 @Emotion/react가 있다. 그리고 styled 라이브러리와 연동해서 사용하는 styled 라이브러리가 있다.

@emotion/react

emotionreact에서는 css라는 함수를 통해서 css={css({스타일객체})} 또는 css={cssstylesheet선언내용}와 같은 식으로 정의해서 사용한다.

css={css({스타일객체})} 로 사용할경우

/** @jsxImportSource @emotion/react */
import { css } from "@emotion/react";

function MyComponent() {
  return (
    <div
      css={css({
        backgroundColor: "Red",
      })}
    >
      나는 빨강
    </div>
  );
}
export default MyComponent;

{cssstylesheet선언내용} 로 사용할경우

/** @jsxImportSource @emotion/react */
import { css } from "@emotion/react";

function MyComponent() {
  return (
    <div
      css={css`
        background-color: Red;
      `}
    >
      나는 빨강
    </div>
  );
}
export default MyComponent;

권장하는 방식은 css()를 별도의 객체로 작성해서 사용하는 방식이다.

/** @jsxImportSource @emotion/react */
import { css } from '@emotion/react'

const danger = css`
  color: red;
`


function MyComponent() {
  return (
    <div
      css={danger}>
      나는 빨강
    </div>
  );
}
export default MyComponent;

물론 css 를 파일로 공유해서 여러군데에서 사용할수도 있다.

const danger = css`
  color: red;
`
const fontSize15 = css`
  fontSize: '1.5rem';
`

export const errorCss = css`
	${danger}
  	fontWeight : 'bold';
`

//아래 처럼 여러개의 스타일을 배열로 넘겨줄수도 있다.
export const largeErrorCss = css([errorCss, fontSize15, {fontStyle: 'italic'}])

@emotion/styled

emotion에서 styled-components와 비슷한 방식으로 작성할수 있도록 도와주는 라이브러리이다.
emotion/react만 사용할경우

라고 써야하지만, styled 를 사용할경우 const MyStyleDiv=styled.div여러스타일들로 작성하여 처럼 사용자정의 태그형식으로 깔끔하게 작성할수 있다.

import styled from '@emotion/styled'  
const Button = styled.button`  
  color: red;  
`

<Button>Click Me!</Button>

설명서 : https://emotion.sh/docs/styled

파라메터(props)를 이용하여 가변스타일 지정

css를 javascript로 작성하는 가장 큰 장점은 역시 변수에 따라서 스타일을 다르게 적용할수 있다는 것이다.

/** @jsxImportSource @emotion/react */
import styled from '@emotion/styled';

interface ButtonProps {
  children: React.ReactNode;
  color?: string;
  background?: string;
}

const StyledButton = styled.button<ButtonProps>`
  padding: 6px 12px;
  border-radius: 8px;
  border: 1px solid lightgray;

  color: ${(props) => props.color || 'gray'};
  background: ${(props) => props.background || 'white'};
`;

const Button: React.FC<ButtonProps> = (props) => {
  return <StyledButton {...props}>{props.children}</StyledButton>;
};

export default Button;

// 사용 할때는

import Button from './Button'; 
...
<Button color="white" background="blue">My Button</Button>

0 comments:

댓글 쓰기