Although I could have easily added a few fixed options to a SelectControl, it makes sense to use the core functionality and extend it wherever possible. The theme.json configuration file allows you to set a number of predefined aspect ratio options, and my React component uses useSettings (see documentation*) from the block-editor package to retrieve these options.
Since the SelectControl component from the core requires the entries in the options array to be in value / label format, I parse the values that come back from useSettings before implementing them in the SelectControl.
import { useSettings } from '@wordpress/block-editor';
import { SelectControl } from '@wordpress/components';
const MyComponent = ({aspectRatio, setAttributes}) => {
const [defaultRatios, themeRatios] = useSettings('dimensions.aspectRatios.default', 'dimensions.aspectRatios.theme');
// Merge core and custom values
const aspectRatios = [...(defaultRatios || []), ...(themeRatios || [])];
// Build an array which I can use in SelectControl
const aspectRatioOptions = aspectRatios.map((ratio) => {
return {
value: ratio.ratio,
label: ratio.name,
};
});
return <SelectControl
label={_x('Aspect ratio', 'SelectControl label', 'mytextdomain')}
value={aspectRatio}
options={aspectRatioOptions}
onChange={(aspectRatio) => setAttributes({ aspectRatioDesktop })} />;
};
(* The possible key values that can be passed to useSettings do not seem to be documented at the moment. Thanks to Aki for pointing me in the right direction).
