이슈
MUI사용 중 chip을 사용할 일이 생겼다.
수많은 옵션을 구현하기 적합하다고 판단해서 chip를 선택했지만 체크박스나 라디오박스처럼 클릭 시
색상이 변한다던지 구분이 되어야하는데 의외로 지원 안 해준다.
정작 clickable 메서드는 만들어 놓고 지원 안 하는 건 무슨 심보일까.

https://mui.com/material-ui/react-chip/
React Chip component - Material UI
Chips are compact elements that represent an input, attribute, or action.
mui.com
나같이 생각한 사람들

에이 설마 하고 찾아보는데 없다.
나 같은 기능을 원하는 인간들이 종종 보이는데 원하는 답변은 안 나온다.
작성 기간을 보니 V4랑 V5랑 혼동되긴 했는데 아무튼 내가 못 찾았으니 없는 거다.
MUI's Chip Component change background color when selected
I'm working in react and using MUI's Chip component. I would like to make it so that it will change the background color once it is selected instead of the generic default color. I have tried usin...
stackoverflow.com
https://github.com/mui/material-ui/issues/10610
[Chip] Add "selected" prop · Issue #10610 · mui/material-ui
I have searched the issues of this repository and believe that this is not a duplicate. Expected Behavior Chip should have an active prop to set the Chip to be visually active or not. Current Behav...
github.com
해결
그래서 그냥 직접 구현해 버렸다.
옵션을 죄다 Array에 때려 박고 클릭이벤트로 value를 string 타입으로 넘겨주고 배열에 있으면 filter함수를 사용해 걸러버리고
없으면 State에 추가해 주는 식으로 급한 대로 동작시켰다.
앞으로 추가될 옵션을 아무리 많이 잡아도 50개 이하이기에 그냥 효율을 버리고 구현에 집중했다.
import { Chip } from "@mui/material";
import React, { useEffect, useState } from "react";
export const Upload = () => {
const options = ["옵션1", "옵션2", "옵션3"];
const [selectedOptions, setSelectedOptions] = useState<string[]>([]);
const handleClick = (value: string) => {
if (selectedOptions.includes(value)) {
setSelectedOptions(selectedOptions.filter((v: string) => v != value));
} else setSelectedOptions([...selectedOptions, value]);
};
useEffect(() => {
console.log(selectedOptions);
}, [selectedOptions]);
return (
<>
{options.map((v: string) => {
return (
<Chip
key={v}
clickable
color={selectedOptions.includes(v) ? "error" : "primary"}
label={v}
onClick={() => handleClick(v)}
/>
);
})}
</>
);
};
아무튼 해결.
후기

아차차...
'React' 카테고리의 다른 글
[Recoil] 상태관리 라이브러리를 통한 상태관리 (0) | 2023.02.15 |
---|---|
React에서 Lottie 적용하기 (0) | 2023.01.26 |
[React-Native] 뜬금없는 서버 모니터링 어플 개발기 (1) | 2023.01.04 |
[React-Native] BottomSheet 사용하기 (0) | 2023.01.02 |