Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

401
Vistas
How to detect screen orientation change in react-native app with a funtion component

I'm making a calculator App for react-native and I want to render different layout for buttons in landscape and portrait mode, how can I do it in a function component

my return:

return (
          <View style={styles.container}>

              <View style={styles.resultContainer}>
                    <Text style={styles.resultText}>
                        {displayValue}
                    </Text>
              </View>

              <View style={styles.inputContainer } >
                  {renderButtons()}

              </View>

          </View>

             );

and my RenderButtons funtion

renderButtons = () =>{

        height = Dimensions.get('window').height
        width = Dimensions.get('window').width

      if(height > width){

        let layouts = buttons.map((buttonRows,index)=>{
            let rowItem = buttonRows.map((buttonItems,buttonIndex)=>{
                return <InputButton
                value={buttonItems}
                handleOnPress={handleInput.bind(buttonItems)}
                key={'btn-'+ buttonIndex}/>
            });
            return <View style={styles.inputRow} key={'row-' + index}>{rowItem}</View>
        });

        return layouts
      }
      else 
      {
        let layouts = buttons_landscape.map((buttonRows,index)=>{
          let rowItem = buttonRows.map((buttonItems,buttonIndex)=>{
              return <InputButton
              value={buttonItems}
              handleOnPress={handleInput.bind(buttonItems)}
              key={'btn-'+ buttonIndex}/>
          });
          return <View style={styles.inputRow} key={'row-' + index}>{rowItem}</View>
      });

      return layouts

      }
    }

of course (height > width) condition doesn't work because apparently the values are undefined, I'm kinda new to JS so please don't be to harsh on me for not knowing the obvious

about 4 years ago · Juan Pablo Isaza
2 Respuestas
Responde la pregunta

0

You can use react-native-orientation-locker

import Orientation from 'react-native-orientation-locker';


  _onOrientationDidChange = (orientation) => {
    if (orientation == 'LANDSCAPE-LEFT') {
      //do something with landscape left layout
    } else {
      //do something with portrait layout
    }
  };

  componentWillMount() {
    //The getOrientation method is async. It happens sometimes that
    //you need the orientation at the moment the js starts running on device.
    //getInitialOrientation returns directly because its a constant set at the
    //beginning of the js code.
    var initial = Orientation.getInitialOrientation();
    if (initial === 'PORTRAIT') {
      //do stuff
    } else {
      //do other stuff
    }
  },

  componentDidMount() {

    Orientation.getAutoRotateState((rotationLock) => this.setState({rotationLock}));
    //this allows to check if the system autolock is enabled or not.

    Orientation.lockToPortrait(); //this will lock the view to Portrait
    //Orientation.lockToLandscapeLeft(); //this will lock the view to Landscape
    //Orientation.unlockAllOrientations(); //this will unlock the view to all Orientations

    //get current UI orientation
    /*
    Orientation.getOrientation((orientation)=> {
      console.log("Current UI Orientation: ", orientation);
    });

    //get current device orientation
    Orientation.getDeviceOrientation((deviceOrientation)=> {
      console.log("Current Device Orientation: ", deviceOrientation);
    });
    */

    Orientation.addOrientationListener(this._onOrientationDidChange);
  },

  componentWillUnmount: function() {
    Orientation.removeOrientationListener(this._onOrientationDidChange);
  }

Another approach can be Here

about 4 years ago · Juan Pablo Isaza Denunciar

0

You can use this library react-native-orientation

Example:

import Orientation from 'react-native-orientation';

 const AppScreen = () => {
  // ...

  const [deviceOrientation, setDeviceOrientation] = React.useState('');

  React.useEffect(() => {
    // The getOrientation method is async. It happens sometimes that
    // you need the orientation at the moment the JS runtime starts running on device.
    // `getInitialOrientation` returns directly because its a constant set at the
    // beginning of the JS runtime.

    // this locks the view to Portrait Mode
    Orientation.lockToPortrait();

    // this locks the view to Landscape Mode
    // Orientation.lockToLandscape();

    // this unlocks any previous locks to all Orientations
    // Orientation.unlockAllOrientations();

    Orientation.addDeviceOrientationListener(handleChangeOrientation);

    return () => {
      Orientation.removeAllListeners(handleChangeOrientation);
      console.log('Bye see you soon ! 👋');
    };
  }, []);


  const handleChangeOrientation = orientation => {
    console.log(' Device orientation change to:', orientation);
    setDeviceOrientation(orientation);
  };

  return (
    <View style={{flex: 1}}>
      <Text>{deviceOrientation}</Text>
    </View>
  );
};

export default AppScreen;
  
about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda