UnitControl allows the user to set a numeric quantity as well as a unit (e.g. px).
Import
import { UnitControl } from '@wordpress/components';
Examples
Default
const Default = () => {
const [ value, setValue ] = useState< string | undefined >( '10px' );
return (
<UnitControl
__next40pxDefaultSize
onUnitChange={fn()}
onFocus={fn()}
onBlur={fn()}
label="Label"
value={ value }
onChange={ ( v, extra ) => {
setValue( v );
onChange?.( v, extra );
} } />
);
};
Press Enter To Change
If the isPressEnterToChange prop is set to true, the onChange callback will not fire while a new value is typed in the input field (you can verify this behavior by inspecting the console’s output).
const PressEnterToChange = () => {
const [ value, setValue ] = useState< string | undefined >( '10px' );
return (
<UnitControl
__next40pxDefaultSize
onUnitChange={fn()}
onFocus={fn()}
onBlur={fn()}
isPressEnterToChange
value={ value }
onChange={ ( v, extra ) => {
setValue( v );
onChange?.( v, extra );
} } />
);
};
Tweaking The Number Input
Most of NumberControl‘s props can be passed to UnitControl, and they will affect its numeric input field.
const TweakingTheNumberInput = () => {
const [ value, setValue ] = useState< string | undefined >( '10px' );
return (
<UnitControl
__next40pxDefaultSize
onUnitChange={fn()}
onFocus={fn()}
onBlur={fn()}
min={0}
max={100}
step="any"
label="Custom label"
value={ value }
onChange={ ( v, extra ) => {
setValue( v );
onChange?.( v, extra );
} } />
);
};
With Single Unit
When only one unit is available, the unit selection dropdown becomes static text.
const WithSingleUnit = () => {
const [ value, setValue ] = useState< string | undefined >( '10px' );
return (
<UnitControl
__next40pxDefaultSize
onUnitChange={fn()}
onFocus={fn()}
onBlur={fn()}
units={CSS_UNITS.slice( 0, 1 )}
value={ value }
onChange={ ( v, extra ) => {
setValue( v );
onChange?.( v, extra );
} } />
);
};
With Custom Units
It is possible to pass a custom list of units. Every time the unit changes, if the isResetValueOnUnitChange is set to true, the input’s quantity is reset to the new unit’s default value.
const WithCustomUnits = () => {
const [ value, setValue ] = useState< string | undefined >( '80km' );
return (
<UnitControl
__next40pxDefaultSize
onUnitChange={fn()}
onFocus={fn()}
onBlur={fn()}
isResetValueOnUnitChange
min={0}
units={[
{
value: 'km',
label: 'km',
default: 1,
},
{
value: 'mi',
label: 'mi',
default: 1,
},
{
value: 'm',
label: 'm',
default: 1000,
},
{
value: 'yd',
label: 'yd',
default: 1760,
},
]}
value={ value }
onChange={ ( v, extra ) => {
setValue( v );
onChange?.( v, extra );
} } />
);
};