I’ve been working on a custom image carousel block for a WordPress client, and wanted to add the built-in aspect ratios as a drop-down control.
Although I could easily have added a few fixed options to a SelectControl
, it makes sense to use and extend core functionality where possible. The theme.json configuration file allows us to configure a set of preset aspect ratio options and this React component uses useSettings
(documentation*) from the block-editor package to fetch them.
Because the SelectControl
component from core requires that the entries of the options array are in value / label format, I parse the values which come back from useSettings
before implementing them through 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 which you can pass to useSettings
apparently remain undocumented. Thanks to Aki for pointing me in the right direction.)
Leave a Reply