React 사용시, 각 컴포넌트마다 해당되는 클래스를 수동으로 매겨주는게 좀 번거롭다.
(ex) 이 버튼 className에는 button--blue
랑 button--small
먹여야지, 저 버튼에는 button--blue
이랑 button--big
이랑 button--round
먹여야지, 저기에는 ...
이때 사용하는 라이브러리가 clsx
npm install clsx
import clsx from "clsx"
clsx({"class-name": booleanValue})
true
false
boolean을 그대로 명시해서 적는 경우import clsx from "clsx";
const result = clsx({
"button": true,
"button-primary": true
})
console.log(result) // "button button-primary"
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}/>
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>
}
// 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>;
}
"ui-button"
는 유지하면서 다른 className역시 언제든 추가 될 수 있는 상태가 된다.