Home > OS >  How to change View Content On Click - React Native
How to change View Content On Click - React Native

Time:12-01

I've been trying to replace a view in React Native, but to no success. The app closes without errors whenever I try <TouchableOpacity onPress={() => {handleChangeMyView();}}> :

What am I doing wrong? How can I make it work?

Thank you all in advance.

import React, {
  useState
} from 'react';

import {
  SafeAreaView,
  View,
  TouchableOpacity,
} from 'react-native';

import MyInitialView from './MyInitialView';

const SiteContainer = () => {
  let MyDynamicView = () => {
    return (
      <View></View>
    );
  };

  const [MyDynamicViewArea, setMyDynamicViewArea] = useState(MyInitialView);

  const handleChangeMyView = () => {
    setMyDynamicViewArea(MyDynamicView);
  };

  return (
    <SafeAreaView>
      {MyDynamicViewArea}
      <TouchableOpacity onPress={() => {handleChangeMyView();}}>
        <View>
          <FontAwesome name="quote-left"></FontAwesome>
        </View>
      </TouchableOpacity>
    </SafeAreaView>
  );
};

export default SiteContainer;

MyInitialView :

import React from 'react';

import {
  View
} from 'react-native';

export default function MyInitialView() {
  return (
    <View></View>
  );
}

CodePudding user response:

You can use boolean value for viewing MyInitialView using useState

  const [toViewMyInitialView, setToViewMyInitialView] = useState(false);

and in handleChangeMyView function set the above value as true

  const handleChangeMyView = () => {
    setToViewMyInitialView(true);
  };

And in the SiteContainer

<SafeAreaView style={styles.siteContainer}>
      // here I don't know a way to display a component in react-native, so 
      // you need to display the component MyInitialView if the 
      // toViewMyInitialView is true and when toViewMyInitialView id false it 
      // display MyDynamicViewArea    
                                                                                                                                            
      {toViewMyInitialView && <MyInitialView/>}
       {!toViewMyInitialView && <MyDynamicViewArea/>}
      <TouchableOpacity onPress={() => {handleChangeMyView()}}>
        <View>
          <FontAwesome name="quote-left"></FontAwesome>
        </View>
      </TouchableOpacity>
    </SafeAreaView>
  • Related