Skip to content

Instantly share code, notes, and snippets.

@glendaviesnz
Created June 15, 2021 03:53
Show Gist options
  • Save glendaviesnz/1a512d3a39cdfb773c9f237b7f6ae42e to your computer and use it in GitHub Desktop.
Save glendaviesnz/1a512d3a39cdfb773c9f237b7f6ae42e to your computer and use it in GitHub Desktop.
Draft image dimensions hood
**
* WordPress dependencies
*/
import { useEffect, useState } from '@wordpress/element';
export default function useDimensionHander(
defaultWidth,
customWidth,
defaultHeight,
customHeight,
onChange
) {
const [ currentWidth, setCurrentWidth ] = useState(
customWidth ?? defaultWidth ?? ''
);
const [ currentHeight, setCurrentHeight ] = useState(
customHeight ?? defaultHeight ?? ''
);
useEffect( () => {
if ( customWidth === undefined && defaultWidth !== undefined ) {
setCurrentWidth( defaultWidth );
}
if ( customHeight === undefined && defaultHeight !== undefined ) {
setCurrentHeight( defaultHeight );
}
}, [ defaultWidth, defaultHeight ] );
function updateDimension( dimension, value ) {
if ( dimension === 'width' ) {
setCurrentWidth( value );
} else {
setCurrentHeight( value );
}
onChange( {
[ dimension ]: value === '' ? undefined : parseInt( value, 10 ),
} );
}
return {
currentWidth,
currentHeight,
updateDimension,
};
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment