How to add SVG icon to a select element
I have a a select element with a custom arrow like this:
<div className="row">
<select>
<!-- options -->
</select>
<Icon />
</div>
Currently only clicking the select element opens the dropdown. I get an error saying I can't put the Icon inside the select element, so what can I do to make clicking the icon also open the select element? Preferably without JS
If you just need a custom arrow icon you can set a background image and appearance: none;
.
If you need an external button to open your select – you'll need to change the size
attribute via js.
let select = document.querySelector("#select");
let options = select.querySelectorAll("option");
function openSelect() {
if (!select.size) {
select.size = options.length;
} else {
closeSelect();
}
}
function closeSelect() {
console.log("close");
select.size = false;
}
html {
font-size: 20px;
}
.select-wrp {
width: 25%;
margin-bottom: 2em;
}
.select-wrp * {
display: block;
width: 100%;
font-size: inherit;
}
.select-custom-icon {
appearance: none;
background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' class='icon icon-prefix-chevron-down' id='icon-prefix-chevron-down' viewBox='0 0 24 24'%3E%3Cpolyline points='6 9 12 15 18 9' fill='none' stroke-linecap='round' stroke-width='4' stroke='red' %3E%3C/polyline%3E%3C/svg%3E%0A");
background-repeat: no-repeat;
background-position: 100% 0%;
}
<div class="select-wrp">
<select class="select-custom-icon">
<option>Option 1</option>
<option>Option 2</option>
<option>Option 3</option>
<option>Option 4</option>
<option>Option 5</option>
<option>Option 6</option>
</select>
</div>
<div class="select-wrp">
<button class="btnOpenSelect" onclick="openSelect()" onblur="closeSelect()">Open Select</button>
<select onblur="closeSelect()" onclick="closeSelect()" id="select">
<option>Option 1</option>
<option>Option 2</option>
<option>Option 3</option>
<option>Option 4</option>
<option>Option 5</option>
<option>Option 6</option>
</select>
</div>