I’m building a block that has, among other things, a FontAwesome icon. I’m currently letting users choose which icon by using a WP <SelectControl>
.
For individual <option>
s, there is a built-in way to add a label. For example:
<SelectControl
value={ icon }
options={[
{ label: '', value: 'fa-address-book' }
]}
/>
Combined with CSS this works great – the dropdown shows the icon itself, making it easy to select for those with good vision. However, I’d like to make this more accessible by adding an aria-label
for each <option>
.
I tried
<SelectControl
value={ icon }
options={[
{ label: '', value: 'fa-address-book', 'aria-label': 'Address book' }
]}
/>
but the aria-label
does not actually render. Is there another way to add it?
The HTML output I’m looking for:
<select id="inspector-select-control-0" class="components-select-control__input">
<option value="fa-address-book" aria-label="Address book"></option>
</select>
I would also be all right with using a screen reader only class in the label itself, but when I try this
<SelectControl
value={ icon }
options={[
{ label: '<span class="show-for-sr">Address book</span>', value: 'fa-address-book' }
]}
/>
the < and > tags show literally in the label rather than creating an actual separate HTML <span>
.
2 Answers
I agree with Nathan’s answer, but you can copy the source and create your own SelectControl
component based on that source. Here’s an example, with basically just the aria-label
addition:
<option
key={ `${ option.label }-${ option.value }-${ index }` }
value={ option.value }
disabled={ option.disabled }
aria-label={ option.ariaLabel || '' }
>
{ option.label }
</option>
And a sample index.js
file demonstrating usage of the custom SelectControl
component:
import SelectControl from './select-control-custom'; // make sure the path is correct
import { withState } from '@wordpress/compose';
const MySelectControl = withState( {
size: '50%',
} )( ( { size, setState } ) => (
<SelectControl
label="Size"
value={ size }
options={ [
{ label: 'Big', value: '100%', ariaLabel: 'Aria label for Big' },
{ label: 'Medium', value: '50%', ariaLabel: 'Aria label for Medium' },
{ label: 'Small', value: '25%', ariaLabel: 'Aria label for Small' },
] }
/>
) );
I.e. Use the ariaLabel
property/key to set the ARIA label. And the above is based on the example here.