• Empleos
  • Sobre nosotros
  • profesionales
    • Inicio
    • Empleos
    • Cursos y retos
  • empresas
    • Inicio
    • Publicar vacante
    • Nuestro proceso
    • Precios
    • Evaluaciones
    • Nómina
    • Blog
    • Comercial
    • Calculadora de salario

0

196
Vistas
Convert from class to functional code in React Native

How do I transfer the follwing code from CLASS to FUNCTIONAL component? This Backhandler part looks like it belongs to React Native so I would have thought that this could be converted to Functional code instead of being within a Class. If there's some other ways that you know of to achieve the same thing handling the back button, please let me know.

Current versions:

"react": "16.13.1",
"react-native": "0.63.4",
"react-navigation": "^4.4.4",
"react-navigation-stack": "^2.10.4"

Code:

import React, { Component } from "react";
import {... BackHandler... } from "react-native";
import { withNavigation } from "react-navigation";


class DetailScreen extends Component {

    componentDidMount() {
        BackHandler.addEventListener('hardwareBackPress', this.handleBackButton.bind(this));
    }

    componentWillUnmount() {
        BackHandler.removeEventListener('hardwareBackPress', this.handleBackButton.bind(this));
    }

    handleBackButton = () => {
        this.props.navigation.pop();
        return true;
    };
}


const styles = StyleSheet.create({
 .......
})


DetailScreen.navigationOptions = () => {
    return {
        header: () => null,
        ...TransitionPresets.SlideFromRightIOS,
    }
}

export default withNavigation(DetailScreen);
almost 3 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

You can add this in your functional component to achieve the same result, the first part allows it to subscribe to the button press on mount, and the return statement happens on unmount to remove the subscription

useEffect(() => {
        const backHandler = BackHandler.addEventListener(
            "hardwareBackPress",
            () => {
                handleBackButton();
            }
        );
        return () => backHandler.remove(); //this might require edits based on your RN version
    }, []);

the syntax used could be different based on your RN version, but basically you subscribe inside this useEffect and unsubscribe in the return

almost 3 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 Nuestro proceso Comercial
Legal
Términos y condiciones Política de privacidad
© 2025 PeakU Inc. All Rights Reserved.

Andres GPT

Recomiéndame algunas ofertas
Necesito ayuda