Home > Software design >  How to refactor React Native function
How to refactor React Native function

Time:03-19

I need to refactor the follow function but not sure how. I dont won't to use useWindowDimensions.

current code

Dimensions.addEventListener('change', ({window:{width,height}})=>{
      if (width<height) {
        setOrientation("PORTRAIT")
      } else {
        setOrientation("LANDSCAPE")
    
      }
    })

I like to convert it into:

 const _onOrientationDidChange = (deviceOrientation) => {
   // get screen Dimensions
  };


useEffect(()=>{
    const screenInfo = Dimensions.addEventListener('change', _onOrientationDidChange)

    return ()=>{
        screenInfo.remove()
    }
},[])

CodePudding user response:

You are not calling _onOrientationDidChange function in addEventListener.

const _onOrientationDidChange = ({ window }) => {
    // get screen Dimensions
    const { height, width } = window;
    if (width < height) {
      setOrientation('PORTRAIT');
    } else {
      setOrientation('LANDSCAPE');
    }
  };

useEffect(() => {
    const screenInfo = Dimensions.addEventListener(
      'change',
      _onOrientationDidChange()
    );

    return () => screenInfo?.remove();
  });
  • Related