Reputation: 2449
I've established a different render logic for tablets and mobile devices. I was wondering if there is a way to get the screen size in inches or maybe even any module to automatically detect if the device is a tablet or not.
The reason I am not using the dimensions api directly to get the screen resolution is that there are many android tablets with lower resolution than many of their mobile counterparts.
Thanks.
Upvotes: 12
Views: 30846
Reputation: 401
Using the below example you can find the device is ios, android, tablet or small device
import { Platform, Dimensions } from 'react-native';
const { width, height } = Dimensions.get('window');
const aspectRatio = height / width;
const isIOS = Platform.OS === 'ios';
const isAndroid = Platform.OS === 'android';
const isTablet = aspectRatio < 1.6; // Assumes 4:3 aspect ratio for tablets
const isSmallDevice = width < 375; // Assumes iPhone 6/7/8 width as small device
// Example usage in a component
const MyComponent = () => {
const deviceType = isTablet ? 'tablet' : 'phone';
const platformType = isIOS ? 'iOS' : 'Android';
return (
<View>
<Text>Device Type: {deviceType}</Text>
<Text>Platform Type: {platformType}</Text>
</View>
);
};
Upvotes: 0
Reputation: 11
use
npm install --save react-native-device-info
then
import Device from 'react-native-device-info';
const isTablet = Device.isTablet();
Upvotes: 1
Reputation: 677
If you don't want to use library react-native-device-info use can use this code below, not sure it't work perfect but may be help
export const isTablet = () => {
let pixelDensity = PixelRatio.get();
const adjustedWidth = screenWidth * pixelDensity;
const adjustedHeight = screenHeight * pixelDensity;
if (pixelDensity < 2 && (adjustedWidth >= 1000 || adjustedHeight >= 1000)) {
return true;
} else
return (
pixelDensity === 2 && (adjustedWidth >= 1920 || adjustedHeight >= 1920)
);
};
Upvotes: 10
Reputation: 629
if(Device.isTablet) {
Object.assign(styles, {
...
});
}
Based on PixelRatio and Screen's height,width.
Upvotes: 0
Reputation: 2449
Based on @martinarroyo's answer, a way to go about it use the react-native-device-info package.
However the android implementation is based on screen resolution. That can be a problem as there are many tablet devices with a lower resolution than many mobile devices and this can cause problems.
The solution I will be using and am suggesting is use react-native-device-info for apple devices and for android devices go with a simple ratio logic of the type:
function isTabletBasedOnRatio(ratio){
if(ratio > 1.6){
return false;
}else{
return true;
}
}
This is not a perfect solution but there are many small tablets with phonelike ratios as well or even phablets ( android is blurry) and this solutions is inclusive towards those as well.
Upvotes: 17
Reputation: 9701
You can use the react-native-device-info package along with the Dimensions API. Check the isTablet()
method and apply different styles according on the result.
Upvotes: 13