I have a component list, in this case is a MUI chips, which has some props (label, callback) and I need to add them to my list when onClick event is triggered. The chip is going to have a label, which is a name selected from a dropdown menu.
I found quite difficult to have a unique chip with the name selected.
//my components list
const [chipList, setChip] = useState([{ chip: "" }]);
const addNewCategory = () => {
if (chipList.length < 5) {
setChip([...chipList, { chip: "" }]);
}
};
//my map to render the component
{chipList.map((widget, index) => (
<CategoryChip key={index} label={subCategory} onDelete={() => handleDelete(index)} />
))}
I am quite sure I have to pass the label inside my useState([{ chip: "" }])
and yes I know, for the moment my chips has all same name because of the label
attribute
You don't need to map() your chipList if your intent is to only show one. The one that is selected.
I'm assuming your subCategory state or prop is the chip info that you chose from the dropdown. You can use findIndex() to show CategoryChip related with that choice.
export default YourComponent = () => {
const [chipList, setChip] = useState([{ chip: "" }]);
const addNewCategory = () => {
if (chipList.length < 5) {
setChip([...chipList, { chip: "" }]);
}
};
...
const renderSelectedChip = () => {
const foundChipIndex = chipList.findIndex(el => el.chip === subCategory);
// I checked for subCategory just to make sure that empty string wasn't a selectable option, but you can remove it if you want
if (!subCategory || foundChipIndex === -1) {
return <></>;
}
return <CategoryChip label={subCategory} onDelete={() => handleDelete(foundChipIndex)} />
))} />
}
return (
<>
...
{renderSelectedChip()}
</>
)
}