• Jobs
  • About Us
  • professionals
    • Home
    • Jobs
    • Courses and challenges
  • business
    • Home
    • Post vacancy
    • Our process
    • Pricing
    • Assessments
    • Payroll
    • Blog
    • Sales
    • Salary Calculator

0

197
Views
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);
about 3 years ago · Juan Pablo Isaza
1 answers
Answer question

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

about 3 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Our process Sales
Legal
Terms and conditions Privacy policy
© 2025 PeakU Inc. All Rights Reserved.

Andres GPT

Recommend me some offers
I have an error