Skip to content
Advertisement

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);

Advertisement

Answer

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

User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement