react native : How can I change the following code to a function component with hooks?

How can I change the following code to a function component with hooks?
In the following code I try to make a modal, but I need to change it to a function component .
I would be happy to help with this.

export default class Example extends Component {
  state = {
    visibleModal: null,
  };

  _renderButton = (text, onPress) => (
    <TouchableOpacity onPress={onPress}>
      <View style={styles.button}>
        <Text>{text}</Text>
      </View>
    </TouchableOpacity>
  );

  _renderModalContent = () => (
    <View style={styles.modalContent}>
      <Text>Hello!</Text>
      {this._renderButton('Close', () => this.setState({ visibleModal: null }))}
    </View>
  );

  render() {
    return (
      <View style={styles.container}>
       
        {this._renderButton('A slower modal', () => this.setState({ visibleModal: 3 }))}
        <Modal isVisible={this.state.visibleModal === 1}>
          {this._renderModalContent()}
        </Modal>
        
        <Modal
          isVisible={this.state.visibleModal === 3}
          animationInTiming={2000}
          animationOutTiming={2000}
          backdropTransitionInTiming={2000}
          backdropTransitionOutTiming={2000}
        >
          {this._renderModalContent()}
        </Modal>
      </View>
    );
  }
}

1 thought on “react native : How can I change the following code to a function component with hooks?”

  1. This would help

    import React, { useState } from 'react';
    import { View, TouchableOpacity, Text, Modal } from 'react-native';
    const App = () => {
      const [visibleModal, setVisibleModal] = useState(undefined);
    
      const _renderButton = (text, onPress) => (
        <TouchableOpacity onPress={onPress}>
          <View style={styles.button}>
            <Text>{text}</Text>
          </View>
        </TouchableOpacity>
      );
    
      const _renderModalContent = () => (
        <View style={styles.modalContent}>
          <Text>Hello!</Text>
          {_renderButton('Close', () => {setVisibleModal(undefined);})}
        </View>
      );
    
      return (
        <View style={styles.container}>
          {_renderButton('A slower modal', () =>{setVisibleModal(3);})}
          <Modal visible={visibleModal === 1 ? true : false}>
            {_renderModalContent()}
          </Modal>
    
          <Modal
            visible={visibleModal === 3 ? true : false}
            animationInTiming={2000}
            animationOutTiming={2000}
            backdropTransitionInTiming={2000}
            backdropTransitionOutTiming={2000}>
            {_renderModalContent()}
          </Modal>
        </View>
      );
    };
    
    export default App;
    
    Reply

Leave a Comment