clsx

Robin·2022년 5월 12일
3

React

목록 보기
3/7

React 사용시, 각 컴포넌트마다 해당되는 클래스를 수동으로 매겨주는게 좀 번거롭다.

(ex) 이 버튼 className에는 button--bluebutton--small 먹여야지, 저 버튼에는 button--blue이랑 button--big이랑 button--round 먹여야지, 저기에는 ...

이때 사용하는 라이브러리가 clsx

사용법

  1. 설치 npm install clsx
  2. 적용 import clsx from "clsx"
  3. 사용 clsx({"class-name": booleanValue})

Basic

  • true false boolean을 그대로 명시해서 적는 경우
  • clsx 리드미 참고 시 더 많은 사용법 확인가능
import clsx from "clsx";

const result = clsx({
	"button": true,
  	"button-primary": true
})

console.log(result) // "button button-primary"

Advanced

  • props를 받아서 적용하는 경우
import React from "react";
import clsx from "clsx";

function RobynZzang(props) {
	const className = clsx({"title": props.really});
  	return <h1 className={className}>Very Zzang Zzang</h1>
}

const element = <RobynZzang really={true}/>

굳이 clsx 사용해서 이렇게 작성하는 이유는?

  • 번거롭고 길다란 if 조건문을 작성하지 않아도 되기 때문이다.
  • 만약 바로위의 RobynZzang 예시를 clsx 없이 if 조건문을 사용해서 다시금 적어보면,
import React from "react";

function RobynZzang(props) {
	let className = ""
    if (props.really) {
    	className = "title"
    }
  	return <h1 className={className}>Very Zzang Zzang</h1>
}

응용 예시 with spread operator and destructing

// Button.js

import React from "react";
import clsx from "clsx"

export default function Button(props) {
    const {className, children, ...rest} = props;
    const classes = clsx(className, "ui-button")
    return <button className={classes} {...rest}>{children}</button>;
}
  • 디폴트 className인 "ui-button"는 유지하면서 다른 className역시 언제든 추가 될 수 있는 상태가 된다.
profile
Always testing, sometimes dog walking

0개의 댓글

관련 채용 정보