skip to Main Content

Below is my React Native Code. When the Tips For Farming button is pressed, there is a Back button at the extreme bottom. You have to scroll down completely to see it. When it is clicked, the home page (the page with the initial buttons) should appear but it is not functioning as expected. Please check my React Native code.

I clicked the Tips For Farming button, scrolled down fully, and clicked on the Back button. I expected the home page to appear. Instead, a blank page appeared. Please help. I want the initial buttons to reappear when the Back button is clicked. Also please explain what I did wrong because ChatGPT couldn’t help me.

import { View, Image, StyleSheet, Animated, Easing, TouchableOpacity, Text, ScrollView } from 'react-native';

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
  },
  logo: {
    width: 200,
    height: 200,
    resizeMode: 'contain',
  },
  buttonContainer: {
    marginTop: -170,
  },
  button: {
    padding: 15,
    borderRadius: 10,
    marginVertical: 10,
    justifyContent: 'center',
    alignItems: 'center',
  },
  yellowButton: {
    backgroundColor: 'yellow',
  },
  grayButton: {
    backgroundColor: 'gray',
  },
  backButton: {
    backgroundColor: 'violet',
    alignSelf: 'center',
  },
  orangeButton: {
    backgroundColor: 'orange',
  },
  greenButton: {
    backgroundColor: 'green',
    borderRadius: 41,
    width: 82,
    height: 82,
    justifyContent: 'center',
    alignItems: 'center',
    marginLeft: 40,
  },
  buttonText: {
    textAlign: 'center',
    color: 'black',
  },
  Heading: {
    color: 'red',
    alignSelf: 'center',
    fontSize: 32,
    paddingTop: 25,
    fontWeight: 'bold',
  },
  SubHeading: {
    color: 'cyan',
    fontSize: 24,
    paddingTop: 20,
    paddingLeft: 20,
    fontWeight: 'bold',
  },
  separatePageContainer: {
    flex: 1,
    justifyContent: 'top',
    alignItems: 'left',
    backgroundColor: 'orange',
    paddingHorizontal: 10,
    paddingBottom: -500,
  },
  separatePageText: {
    color: 'white',
    fontSize: 18,
    textAlign: 'left',
    paddingHorizontal: 20,
    marginTop: 40,
  },
  table: {
    flexDirection: 'row',
    marginTop: 20,
    borderStyle: 'solid',
    borderWidth: 0.5,
  },
  tableHeader: {
    flex: 1,
    padding: 10,
    backgroundColor: 'gray',
    color: 'white',
    fontWeight: 'bold',
    borderStyle: 'solid',
    borderWidth: 1,
  },
  tableRow: {
    flexDirection: 'row',
    borderStyle: 'solid',
    borderWidth: 0.5,
    backgroundColor: 'skyblue',
  },
  tableCell: {
    flex: 1,
    padding: 10,
    color: 'magenta',
    borderStyle: 'solid',
    borderWidth: 1,
    flexWrap: 'wrap',
  },
  Image: {
    marginTop: 20,
    alignSelf: 'center',
    maxWidth: 300,
    maxHeight: 200,
  },
});

const DisplayLogo = () => {
  const [showSeparatePage, setShowSeparatePage] = useState(false);
  const [showBackButton, setShowBackButton] = useState(false);
  const translateY = new Animated.Value(700);
  const logoOpacity = new Animated.Value(1);
  const buttonOpacity = new Animated.Value(0);
  const backgroundColor = new Animated.Value(0);
  const rowData = [
    { sn: '1', step: 'Ploughing', implement: 'Wooden or iron ploughs' },
    { sn: '2', step: 'Levelling', implement: 'Wooden or iron levellers' },
    { sn: '3', step: 'Manuring', implement: 'Manually or with drills' },
    { sn: '4', step: 'Sowing', implement: 'Ploughs, hand sowing, seed drills' },
    { sn: '5', step: 'Irrigation', implement: 'Tubewells, sprinklers' },
    { sn: '6', step: 'Weeding', implement: 'Trowel (khurpa)' },
    { sn: '7', step: 'Crop protection', implement: 'Sprayers' },
    { sn: '8', step: 'Harvesting', implement: 'Sickle, harvesting machine' },
    { sn: '9', step: 'Threshing', implement: 'Animals, threshers, combines' },
    { sn: '10', step: 'Crop storage', implement: 'Jute bags, wooden, clay or metal containers' },
  ];

  useEffect(() => {
    const logoAnimation = Animated.sequence([
      Animated.timing(translateY, {
        toValue: 250,
        duration: 1000,
        useNativeDriver: true,
        easing: Easing.inOut(Easing.ease),
      }),
      Animated.delay(2000),
      Animated.parallel([
        Animated.timing(translateY, {
          toValue: -50,
          duration: 1000,
          useNativeDriver: true,
          easing: Easing.inOut(Easing.ease),
        }),
        Animated.timing(logoOpacity, {
          toValue: 0,
          duration: 1000,
          useNativeDriver: true,
        }),
      ]),
    ]);

    const buttonsAnimation = Animated.timing(buttonOpacity, {
      toValue: 1,
      duration: 500,
      delay: 500,
      useNativeDriver: true,
    });

    Animated.sequence([logoAnimation, buttonsAnimation]).start();

    setTimeout(() => {
      Animated.timing(backgroundColor, {
        toValue: 1,
        duration: 500,
        useNativeDriver: false,
      }).start();
    }, 3000);

    return () => {
      translateY.setValue(500);
      logoOpacity.setValue(1);
      buttonOpacity.setValue(0);
      backgroundColor.setValue(0);
    };
  }, []);

  const handleTipsForFarmingPress = () => {
    setShowSeparatePage(true);
    setShowBackButton(true);
    Animated.timing(buttonOpacity, {
      toValue: 0,
      duration: 500,
      useNativeDriver: true,
    }).start();
    Animated.timing(backgroundColor, {
      toValue: 2,
      duration: 500,
      useNativeDriver: false,
    }).start();
  };
  const handleBackButtonPress = () => {
    setShowSeparatePage(false);
    setShowBackButton(false);
    Animated.timing(buttonOpacity, {
      toValue: 1,
      duration: 500,
      useNativeDriver: true,
    }).start();
    Animated.timing(backgroundColor, {
      toValue: 1,
      duration: 500,
      useNativeDriver: false,
    }).start();
  };

  if (showSeparatePage) {
    return (
      <ScrollView contentContainerStyle={{ flexGrow: 1 }}>
        <View style={{ ...styles.separatePageContainer }}>
          <Text style={styles.separatePageText}>
            Farming or agriculture is very important for survival, and some proper techniques have to be used. The following are the basic steps for farming.
          </Text>

          {/* Table */}
          <View style={styles.table}>
            <Text style={{ ...styles.tableHeader }}>S. No.</Text>
            <Text style={{ ...styles.tableHeader }}>Steps</Text>
            <Text style={{ ...styles.tableHeader }}>Implements</Text>
          </View>

          {/* Rows */}
          {rowData.map((row, index) => (
            <View key={index} style={styles.tableRow}>
              <Text style={{ ...styles.tableCell }}>{row.sn}</Text>
              <Text style={{ ...styles.tableCell }}>{row.step}</Text>
              <Text style={{ ...styles.tableCell }}>{row.implement}</Text>
            </View>
          ))}

          <Text style={styles.Heading}>
            Ploughing
          </Text>
          <Text style={styles.separatePageText}>
            The process of loosening and turning the soil is called tilling or ploughing. It helps in adding air to the soil, allowing the roots to penetrate deeper, bringing nutrient-rich soil to the top, helping in the growth of earthworms, etc.
          </Text>
          <Text style={styles.separatePageText}>
            The implements used for ploughing are plough, hoe, and cultivator.
          </Text>
          <Image source={require('./assets/Plough.jpg')} style={styles.Image}></Image>
          <Image source={require('./assets/Hoe.jpg')} style={styles.Image}></Image>
          <Image source={require('./assets/Cultivator.png')} style={styles.Image}></Image>
          <Text style={styles.separatePageText}>
            Generally, cultivator is the best one to use in order to save time and labour. It can break up soil, remove seeds, and penetrate large depths in order to sufficiently break up the soil for soil-bed preparation.
          </Text>
          <Text style={styles.Heading}>
            Levelling
          </Text>
          <Text style={styles.separatePageText}>
            The soil has to be levelled after ploughing. It helps in uniform distribution of water in the field during irrigation and reduces irrigation time, prevents the loss of moisture from ploughed soil, and increases yield and quality.
          </Text>
          <Text style={styles.Heading}>
            Manuring
          </Text>
          <Text style={styles.separatePageText}>
            The process of applying organic minerals and adding nutrients to the soil is called manuring. This is done for proper mixing of manure with soil to increase soil fertility before seeds are sown in the field.
          </Text>
          <Text style={styles.Heading}>Sowing</Text>
          <Text style={styles.separatePageText}>
            Once the soil is prepared, seeds are sown in it. While sowing seeds the following points need to be kept in mind.
          </Text>
          <Text style={styles.separatePageText}>
          Seeds should be of good quality, healthy and free from diseases.
          </Text>
          <Text style={styles.separatePageText}>
          They must be planted at the proper depth in the soil. If planted too deep in the soil, they cannot respire and their shoots may not be able to push through the soil. If planted on the surface, they will be eaten by birds.
          </Text>
          <Text style={styles.separatePageText}>
          Seeds require water for germination. The soil should, therefore, have water in it. However, if there is too much water, seeds will not germinate properly.
          </Text>
          <Text style={styles.separatePageText}>
          Seeds should be sown at proper distances. If they are too close, they will compete and hence will not get enough water, sunlight and nutrients for their normal growth and development. If they are too far apart, there is wastage of field space.
          </Text>
          <Text style={styles.separatePageText}>
          A seed drill should be used for sowing seeds as it sows seeds at equal distances and at proper depths.
          </Text>
          <Image source={require('./assets/Seed_Drill.jpg')} style={styles.Image}></Image>
          <Text style={styles.Heading}>
            Irrigation
          </Text>
          <Text style={styles.separatePageText}>
          Irrigation means supplying water to crops in the field. It provides water to the plants for their various physiological activites like photosynthesis, transpiration, ascent of sap, etc. Water helps in the absorption of minerals from the soil. Water is essential for germination of seeds and elongation of roots. Water protects crops from frost or from dry hot air currents. Moreover, farmers should not depend on rainfalls for their crops and instead have their own irrigation system.
          </Text>
          <Text style={styles.separatePageText}>
          The modern ways of irrigation are pumps, canals, sprinkler system and drip irrigation.
          </Text>
          <Image source={require('./assets/Pump.jpg')} style={styles.Image}></Image>
          <Image source={require('./assets/Canal.jpg')} style={styles.Image}></Image>
          <Image source={require('./assets/Sprinkler_System.jpg')} style={styles.Image}></Image>
          <Image source={require('./assets/Drip_Irrigation.jpg')} style={styles.Image}></Image>
          <Text style={styles.Heading}>
            Weeding
          </Text>
          <Text style={styles.separatePageText}>
          Weeds are unwanted plants that grow along with the main crops. They compete with the main crops for water, minerals and sunlight and, therefore, reduce crop yield.
          </Text>
          <Text style={styles.separatePageText}>
          The best time to remove weeds is when the soil is damp and moist as damp soils are loose and make it easier to remove weeds with their roots. Weeding can be done in the following ways.
          </Text>
          <Text style={styles.SubHeading}>
            Mechanical Methods
          </Text>
          <Text style={styles.separatePageText}>
            Weeds are removed manually by pulling them out with hands or by using a khurpa (trowel), hoe or a rake. In small fields, hand pulling or by means of a khurpa or hoe is the appropriate method. But in large fields, mechanical weeding is done by methods like ploughing, harrowing, intercultivation, flooding or burning. This method is time consuming and involves a lot of labour.
          </Text>
          <Image source={require('./assets/Weeding1.jpg')} style={styles.Image}></Image>
          <Text style={styles.SubHeading}>
            Chemical Methods
          </Text>
          <Text style={styles.separatePageText}>
            Weeding is also done by spraying special chemicals called herbicides or weedicides, with the help of a sprayer. Some common weedicides are dalapon, metachlor, siniazine, 2, 4-D (2, 4-dichlorophenoxy acetic acid), MCPA (2-methyl-4-chloro-1-phenoxy acetic acid) and Butachlor.
          </Text>
          <Text style={styles.separatePageText}>
            However, weedicides are poisonous and the grains must be properly washed before being consumed. Since weedicides are poisonous, spraying may affect the health of farmers. Therefore, farmers should be careful while using weedicides. It is advised that the farmer should cover his mouth and nose with cloth while spraying.
          </Text>
          <Image source={require('./assets/Weeding2.jpg')} style={styles.Image}></Image>
          <Text style={styles.SubHeading}>
            Biological Methods
          </Text>
          <Text style={styles.separatePageText}>
            Research for evolving safer methods to kill weeds is going on. For example, insects that attack only specific weeds have been used to control those weeds. However, it is necessary to check the reproduction of these insects. For example, cochineal insect in Tamil Nadu is used to eliminate prickly pear (Opuntia) from the crop fields. Experiments have been conducted to attract and trap the male population of the insects, in order to check their reproduction.
          </Text>
          <Image source={require('./assets/Weeding3.jpg')} style={styles.Image}></Image>
          <Image source={require('./assets/Weeding4.jpg')} style={styles.Image}></Image>
          <Text style={styles.Heading}>
            Crop Protection
          </Text>
          <Text style={styles.separatePageText}>
            Crops can be protected from stray animals like cows and buffaloes by putting wire fence all around the field. Birds can be scared away from fields by placing scarecrows or by beating drums.
          </Text>
          <Text style={styles.separatePageText}>
            Pests can be controlled by pesticides which are poisonous chemicals. Pesticides kill pests as well as their eggs and larvae but do not affect the plant.
          </Text>
          <Image source={require('./assets/Scarecrow.jpg')} style={styles.Image}></Image>
          <Text style={styles.Heading}>
            Harvesting
          </Text>
          <Text style={styles.separatePageText}>
            Once the crop matures it is harvested, i.e., cut and gathered. This may be done manually by using a sickle, or by using a machine called a harvester.
          </Text>
          <Image source={require('./assets/Harvester.jpg')} style={styles.Image}></Image>
          <Text style={styles.separatePageText}>
            Next, the grain is separated from the cut or harvested crop through threshing. It can be done manually or by using a thresher. A combine is ued for both harvesting and threshing.
          </Text>
          <Image source={require('./assets/Threshing.jpg')} style={styles.Image}></Image>
          <Text style={styles.separatePageText}>
            After threshing, the grain is separated from the chaff by winnowing.
          </Text>
          <Image source={require('./assets/Winnowing.jpg')} style={styles.Image}></Image>
          <Text style={styles.Heading}>
            Crop Storage
          </Text>
          <Text style={styles.separatePageText}>
            Crops are stored after harvesting. Generally, a buffer stock is maintained to compensate if the monsoons fail anytime.
          </Text>
          <Text style={styles.SubHeading}>
            Gunny Bags
          </Text>
          <Text style={styles.separatePageText}>
            Gunny bags are jute bags. They are filled with food grains and are stacked in large godowns on wooden platforms. They are stored at about 10-15 cm above the ground and above 70 cm away from the wall. The godowns are made free of microbes, insects and rodents by spraying pesticides and insecticides.
          </Text>
          <Image source={require('./assets/Gunny_Bag.jpg')} style={styles.Image}></Image>
          <Text style={styles.SubHeading}>
            Silos And Granaries
          </Text>
          <Text style={styles.separatePageText}>
            Silos are tall cylindrical containers used for bulk storage of grains. These are used specially by government agencies like Food Corporation of India (FCI). Grain silos facilitate easy inspection, fumigation, protection from pests and temperature control. Granaries are large buildings where grains are stored inside gunny bags, etc.
          </Text>
          <Image source={require('./assets/Silos.jpg')} style={styles.Image}></Image>
          <Image source={require('./assets/Granary.jpg')} style={styles.Image}></Image>
          {showBackButton && (
            <TouchableOpacity
              style={{ ...styles.button, ...styles.backButton, marginTop: 60 }}
              onPress={handleBackButtonPress}
            >
              <Text style={styles.buttonText}>Back</Text>
            </TouchableOpacity>
          )}
        </View>
      </ScrollView>
    );
  }

  return (
    <ScrollView contentContainerStyle={{ flexGrow: 1 }}>
      <Animated.View style={{ ...styles.container, backgroundColor: backgroundColor.interpolate({
        inputRange: [0, 1, 2],
        outputRange: ['white', 'skyblue', 'orange'],
      }) }}>
        <Animated.Image
          style={{
            ...styles.logo,
            transform: [{ translateY }],
            opacity: logoOpacity,
          }}
          source={require('./assets/Logo.png')}
        />

        <Animated.View style={{ ...styles.buttonContainer, opacity: buttonOpacity }}>
          {/* Yellow buttons */}
          {['Tips For Farming', 'Weather Updates', 'Buy Implements', 'Sell Harvest', 'Discuss On Forums', 'Donate'].map(
            (buttonName, index) => (
              <TouchableOpacity
                key={index}
                style={{ ...styles.button, ...styles.yellowButton }}
                onPress={() => {
                  if (buttonName==='Tips For Farming') {
                    handleTipsForFarmingPress()}}
                }
              >
                <Text style={styles.buttonText}>{buttonName}</Text>
              </TouchableOpacity>
            )
          )}

          {/* Gray buttons */}
          <View style={{ flexDirection: 'row' }}>
            {['Help', 'Settings'].map((buttonName, index) => (
              <TouchableOpacity
                key={index}
                style={{ ...styles.button, ...styles.grayButton, marginLeft: 10 }}
                onPress={() => console.log(`Button pressed: ${buttonName}`)}
              >
                <Text style={styles.buttonText}>{buttonName}</Text>
              </TouchableOpacity>
            ))}
          </View>

          {/* Orange button */}
          <TouchableOpacity
            style={{ ...styles.button, ...styles.orangeButton }}
            onPress={() => console.log(`Button pressed: Return Feedback`)}
          >
            <Text style={styles.buttonText}>Return Feedback</Text>
          </TouchableOpacity>

          {/* Green button */}
          <TouchableOpacity
            style={{ ...styles.button, ...styles.greenButton }}
            onPress={() => console.log(`Button pressed: Contact`)}
          >
            <Text style={styles.buttonText}>Contact</Text>
          </TouchableOpacity>
        </Animated.View>
      </Animated.View>
    </ScrollView>
  );
};

export default DisplayLogo;```

2

Answers


  1. An onPress function should always be written as follows, more explanation about it can be found here

                <TouchableOpacity
                  style={{ ...styles.button, ...styles.backButton, marginTop: 60 }}
                  onPress={() => handleBackButtonPress()}
                >
                  <Text style={styles.buttonText}>Back</Text>
                </TouchableOpacity>
    
    Login or Signup to reply.
  2. The problem is that your animations runs only once when component mounted because useEffect does not take any dependency but you need to start animation when showSeparatePage changed. So give it as dependency to useEffect.
    it should look like this

    useEffect(() => {
      // Your code ...
    }, [ showSeperatePage ])
    

    As an second advice for next time please make your code more readable with cleaning unnecessary components(like images and texts);

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search