marudy / react-native-responsive-screen

Make React Native views responsive for all devices with the use of 2 simple methods
MIT License
1.55k stars 141 forks source link

Feature request - is there a way to have some sort of stylesheet-based listener? #95

Open haveamission opened 3 years ago

haveamission commented 3 years ago

I was just thinking - is it possible to have a stylesheet based listener? Right now, it seems like you need to add the listener into each and every single component you want to resize, but I want to use this with React Native Web, and update styles upon window resize.

Having to include the styles in every component I use seems like writing a bunch of code, and couples the styles very heavily to the code in question.

Is there a better, more decoupled way to use this library?

gregfenton commented 3 years ago

I'm not clear on what you mean. If you want to use the width and height functions in a component, you'll need to import them or fetch them via a hook (e.g. Context API). In my components where I use them, I have:

import {
  widthPercentageToDP as wPct,
  heightPercentageToDP as hPct,
} from 'react-native-responsive-screen';

But I only have the listener in one place in my app, at the very top of the component tree:

const App = () => {
  const [responsiveScreen, setResponsiveScreen] = useState();

  useEffect(() => {
    listenOrientationChange({setStateHook: setResponsiveScreen});
    return () => removeOrientationListener();
  });

  return <Providers />;
}

(Note: I'm using the version from this Pull Request I created that adds support for functional components/hooks as used in the example above, but you could achieve similar with class components and the existing setState capability of the main release)