khevamann / rn-responsive-styles

Responsive styles for react-native and react-native-web
MIT License
39 stars 3 forks source link

Know if device is larger or lower than breakpoint #20

Closed matziol closed 7 months ago

matziol commented 1 year ago

Hi! Is there any way to know if device size is larger or lower than specific breakpoint? I want to render something conditionally if device width > DEVICE_SIZES.MD and it would be useful to have something like isDeviceLarger and isDeviceSmaller helpers. I did not find way in Readme or maybe I'm missing something?

Thank you for this lib anyway, it's really useful!

khevamann commented 1 year ago

Hi @matziol, I am assuming you are talking about conditional rendering not styling. If you are talking about styling then you can use: minSize and maxSize to do what you are talking about. https://github.com/khevamann/rn-responsive-styles#simple-media-queries

If you are talking about rendering which I am assuming then there is no current way. I will consider adding that as it wouldn't be too difficult, I just want to keep the API as clear and simple as possible. Maybe an additional helper that uses useDeviceSize internally. I will think about this some more and get back to you hopefully tomorrow.

matziol commented 1 year ago

Yes, I'm talking about conditional rendering. I figured out a way to achieve what I want by using minSize returned value and splitting it by +, then checking if array contains device size returned from useDeviceSize hook. Currently I'm using a helper that looks like this:

import { minSize, DEVICE_SIZES } from 'rn-responsive-styles';
/**
 *
 * @param deviceSize size provided by `useDeviceSize` hook
 * @param minimumSize the minimum size that meets the rule
 * @returns true if deviceSize >= minimumSize, false otherwise
 */

const isDeviceMinimumSize = (deviceSize: DEVICE_SIZES, minimumSize: DEVICE_SIZES) => {
    const largerBreakpoints = minSize(minimumSize).split('+');
    if (largerBreakpoints.length < 1) {
        return false;
    }

    return largerBreakpoints.includes(deviceSize);
};

export { isDeviceMinimumSize };

I'm using it in component like:

export const ExampleComponent = () => {
  const deviceSize = useDeviceSize();
  const isDeviceMinLarge = isDeviceMinimumSize(deviceSize, DEVICE_SIZES.LG);
  const isDeviceMinMedium = isDeviceMinimumSize(deviceSize, DEVICE_SIZES.MD);

  return (
    <View>
      {isDeviceMinLarge && (
        <Text>I am only on large or extra large screen</Text>
      )}
      {isDeviceMinMedium ? (
        <Text>I am on medium, large and extra large screen</Text>
      ) : (
        <Text>I am on sizes below medium - small and extra small!</Text>
      )}
    </View>
  );
};

Hope it'll be helpful!