조건에 따라 class를 추가 / 삭제 할 수 있는 react package이다.
사용법은 간단하다.
import cn from "classnames";
const [sidebar, setSidebar] = useState(false);
<Container className={cn("sidebar", {open: sidebar})}>
</Container>
Container의 기본 class는 "sidebar"이며 sidebar가 true일 경우 key의 대한 value값이 true이기에 key 값인 "open"을 toggleClass로 달아줄 수 있다.
cn("foo", "bar"); // "foo bar" cn("foo", {bar : true}); // "foo bar" cn({"foo-bar" : true}); // "foo-bar" cn({"foo-bar" : false}); cn({foo : true}, {bar : true}); // "foo bar" cn({foo : true, bar : true}); // "foo bar"
let buttonType = "primary";
classNames({ [`btn-${buttonType}`] : true });
const btnClass = cn(‘btn', this.props.className, {
'btn-pressed': this.state.isPressed,
'btn-over': !this.state.isPressed && this.state.isHovered
});
component 로직을 재사용 가능한 hook으로 만드는 것
const [id, onChangeId] = useInput('');
/hooks/useInput.js
import { useState, useCallback } from 'react';
export default (initValue = null) => {
const [value, setValue] = useState(initValue);
const handler = useCallback((e) => {
setValue(e.target.value);
}, []);
return [value, handler];
};
🔗 Collection of React Custom Hooks
https://nikgraf.github.io/react-hooks/
https://github.com/rehooks/awesome-react-hooks