I am building a multi-select dropdown and want to hide the options as soon as user picks one option, but I am unable to hide the dropdown after selectedCategoriesData
state is updates since the setShowCategories(false);
update stops the selectedCategoriesData
state from updating.
How to ensure that selectedCategoriesData
state is updated first and then setShowCategories
.
Please read the comment for my problem
Here are the files:
Filter.jsx:
import classes from "./Filter.module.css";
const Filter = ({ categories }) => {
const [selectedCategoriesData, setSelectedCategoriesData] = useState([]);
const [showCategories, setShowCategories] = useState(false);
const handleCategoryInput = (e) => {};
const handleCategorySelect = (categoryChosen) => {
setSelectedCategoriesData([...selectedCategoriesData, categoryChosen]);
// setShowCategories(false); <---- This is causing not to update the selectedCategoriesData state, why ? I also want to hide the dropdown of options, so I need to set setShowCategories to false AFTER the selectedCategoriesData state is updated.
};
return (
<div className={classes.filter_container}>
<div className="category_filter">
<label htmlFor="ctgry">Category</label>
<input
className={classes.category_select}
onChange={handleCategoryInput}
onFocus={() => setShowCategories(true)}
onBlur={() => setShowCategories(false)}
></input>
{showCategories && (
<ul className={classes.categories_data}>
{categories.map((category, index) => (
<li tabIndex={0} key={index} onClick={() => handleCategorySelect(category)}>
<span>{category}</span>
</li>
))}
</ul>
)}
</div>
</div>
);
};
export default Filter;
Filter.module.css :
.filter_container {
margin-left: 100px;
}
.filter_container label {
font-size: 1.6rem;
font-weight: 600;
}
.category_select {
min-width: 20rem;
border: 1px solid #494949;
padding: 1rem;
font-size: 1.4rem;
display: block;
}
.categories_data {
border: 1px solid gray;
border-top: none;
font-size: 1.4rem;
max-height: 20rem;
width: 20rem;
overflow-x: hidden;
overflow-y: hidden;
}
.categories_data:hover {
overflow-y: scroll;
overflow-x: hidden;
}
.categories_data li span {
display: inline-block;
padding: 0.65rem 0.8rem;
}
.categories_data li:hover {
background-color: #e2e2e2;
cursor: pointer;
}
.categories_data::-webkit-scrollbar {
width: 1rem; /* width of the entire scrollbar */
}
.categories_data::-webkit-scrollbar-track {
background: transparent; /* color of the tracking area */
}
.categories_data::-webkit-scrollbar-thumb {
background-color: #4b4b4b; /* color of the scroll thumb */
border-radius: 20px; /* roundness of the scroll thumb */
border: 3px solid #fff;
/* creates padding around scroll thumb */
}
categories props is array of ['category-1', 'category-2', 'category-3', 'category-4', 'category-5', 'category-6']