I want to show select option list on hover, but it’s not working:
<div className="rating-option">
<select
id="rating"
className="rating"
value={rating}
onChange={(e) => setRating(e.target.value)}
>
<option value="">Select Rating</option>
<option value="1">1- Bad</option>
<option value="2">2- Fair</option>
<option value="3">3- Good</option>
<option value="4">4- Very good</option>
<option value="5">5- Excelent</option>
</select>
</div>
CSS applied to that code:
.rating-option {
position: relative;
margin: 20px;
padding: 20px;
display: flex;
}
.rating-option:hover .rating {
display: list-item;
background-color: red;
}
#rating {
position: absolute;
}
You can’t trigger the display of the options list on hover because it is controlled by the browser itself.
But, you can do a similar effect using custom dropdowns and a React-based approach.
import React, { useState } from 'react';
const CustomSelect = () => {
const [isHovered, setIsHovered] = useState(false);
const [selectedValue, setSelectedValue] = useState('');
const options = [
{ value: '', label: 'Select Rating' },
{ value: '1', label: '1- Bad' },
{ value: '2', label: '2- Fair' },
{ value: '3', label: '3- Good' },
{ value: '4', label: '4- Very good' },
{ value: '5', label: '5- Excellent' },
];
const handleMouseEnter = () => setIsHovered(true);
const handleMouseLeave = () => setIsHovered(false);
return (
<div
className="rating-option"
onMouseEnter={handleMouseEnter}
onMouseLeave={handleMouseLeave}
>
<div className="custom-select">
{selectedValue ? options.find(option => option.value === selectedValue).label : 'Select Rating'}
</div>
{isHovered && (
<ul className="custom-options">
{options.map(option => (
<li
key={option.value}
onClick={() => setSelectedValue(option.value)}
className={option.value === selectedValue ? 'selected' : ''}
>
{option.label}
</li>
))}
</ul>
)}
</div>
);
};
export default CustomSelect;
Update your CSS File
.rating-option {
position: relative;
width: 200px;
margin: 20px;
padding: 10px;
border: 1px solid #ccc;
cursor: pointer;
}
.custom-select {
padding: 10px;
background-color: #f9f9f9;
border: 1px solid #ccc;
text-align: center;
}
.custom-options {
position: absolute;
top: 100%;
left: 0;
width: 100%;
border: 1px solid #ccc;
background-color: #fff;
z-index: 1000;
list-style: none;
padding: 0;
margin: 0;
}
.custom-options li {
padding: 10px;
cursor: pointer;
}
.custom-options li:hover, .custom-options li.selected {
background-color: #f0f0f0;
}
4