There is no dedicated hook or event for this to listen for. Instead use the same data core uses to figure this out:
select( 'core/editor' ).getDeviceType()
e.g. in a react component:
const { deviceType } = useSelect( ( select ) => select( 'core/editor' ).getDeviceType(), [] );
return <h1>{ deviceType }</h1>;
Then you can declare deviceType
a dependency on any effect or reducer hooks you have
Did you mean __experimentalGetPreviewDeviceType to pull the data from central data ? –
If you do this you’ll get a warning that it’s deprecated and to use getDeviceType
instead.
If you wanted to instead try to listen for the change of the event without using useSelect
, you’d need to:
- register to watch
core/editor
viawp.data
‘s subscribe method - every time
core/editor
changes you’d need to double check the device type value to see if it has changed ( you can’t subscribe to portions of the store, it’s only the entire store ) - when the store changes, and the device type no longer matches your own copy, update your copy of the data
- note that this copy would need to be in a data store, it can’t be in react state
- you would then need
useSelect
to fetch your copy, so why bother?
- double check this on every WP release and Gutenberg plugin update as it might change
What Are Device Types?
This may not work how you expect it to, there are 3 device types values, Mobile
, Desktop
, and Tablet
, which are fed into useResizeCanvas
:
This hook then hardcodes the canvas size of the editor based on those 3 strings. There’s no configuring these to match your themes breakpoints, and there’s no “system” to hook into, or ways to add more.
None of this translates to the PHP/server side, or shows up in themes. There are no ways to store settings on a site/block/template for each device type, it’s just how the editor knows which canvas size to show